天天看點

jQuery擷取元素位址

一。擷取元素可以友善我們來計算元素怎麼擺放的問題。

       offset: 擷取比對元素在目前視口的相對偏移。也就是目前元素到頁面頂部的距離。

       position: 擷取比對元素相對父元素的偏移。

       scrollTop: 擷取比對元素相對滾動條頂部的偏移。

       scrollLeft: 擷取比對元素相對滾動條左側的偏移。

      window.pageXOffset: 表示浏覽器X軸(水準)滾動條的偏移距離。(相容:ie9/10、chrome、firefox)

      window.pageYOffset: 表示浏覽器Y軸(垂直)滾動條的偏移距離。(相容:ie9/10、chrome、firefox)

二。jQuery的處理。

      $(window).height() :擷取螢幕的可視高度。

   $(window).width() :擷取螢幕的可視寬度。

三。執行個體.

jQuery擷取元素位址
jQuery擷取元素位址
jQuery擷取元素位址

看上面的三張圖,一個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);

        }
    }
}