`

jQuery获取元素地址

 
阅读更多

一。获取元素可以方便我们来计算元素怎么摆放的问题。

offset: 获取匹配元素在当前视口的相对偏移。也就是当前元素到页面顶部的距离。

position: 获取匹配元素相对父元素的偏移。

scrollTop: 获取匹配元素相对滚动条顶部的偏移。

scrollLeft: 获取匹配元素相对滚动条左侧的偏移。

window.pageXOffset:表示浏览器X轴(水平)滚动条的偏移距离。(兼容:ie9/10、chrome、firefox)

window.pageYOffset: 表示浏览器Y轴(垂直)滚动条的偏移距离。(兼容:ie9/10、chrome、firefox)


二。jQuery的处理。

$(window).height() :获取屏幕的可视高度。

$(window).width() :获取屏幕的可视宽度。


三。实例.

看上面的三张图,一个dialog用户地方不同显示的方式也发生了变化,此时就需要计算对应元素所在位置了。

代码如下:

function showPrompt(){
    var list = $('.outer-inner-item .item li');
    for(var i in list){
        list[i]. onmouseenter = function() {
            clearTimeout(time);
            var top = $('.outer-inner-item .item li').offset().top;
            var left = $(this).offset().left;
            var offsetTop = top - window.pageYOffset;
            var visualHeight = $(window).height()/2 + 36;
            var visualWidth =  $(window).width()/2;
            for(var i in list){
                list.eq(i).find($('.dialog')).css('display','none');
                list.eq(i).find($('.dialog .arrow-bottom')).css({ display: 'none'});
                list.eq(i).find($('.dialog .arrow-top')).css({ display: 'none'});
            }
            if(offsetTop > visualHeight){
                $(this).find($('.dialog .arrow-bottom')).css({ display: 'block'});
                $(this).find($('.dialog .arrow-top')).css({ display: 'none'});
                $(this).find($('.dialog')).css({ bottom: '110px',top: 'auto',display:'block'})
            }else{
                $(this).find($('.dialog .arrow-bottom')).css({ display: 'none'});
                $(this).find($('.dialog .arrow-top')).css({ display: 'block'});
                $(this).find($('.dialog')).css({ top: '110px',bottom:'auto',display:'block'})
            }
            if(left < visualWidth){
                $(this).find($('.dialog .arrow-bottom')).css({right:'auto',left:'30px'});
                $(this).find($('.dialog .arrow-top')).css({right:'auto',left:'30px'});
                $(this).find($('.dialog')).css({right:'auto',left:0});
            }else{
                $(this).find($('.dialog .arrow-top')).css({right:'30px',left:'auto'});
                $(this).find($('.dialog .arrow-bottom')).css({right:'30px',left:'auto'});
                $(this).find($('.dialog')).css({right:0,left:'auto'});
            }
        };
        list[i].onmouseleave  = function() {
            var data = this;
            time = setTimeout(function(){
                $(data).find($('.dialog')).css('display','none');
            },1000);

        }
    }
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics