3

如果使用下面的代碼,當我的下拉菜單落在瀏覽器窗口區域以外時,請重新定位我的下拉菜單。然而,它沒有在Internet Explorer 7工作和8如果窗口靠近邊緣,重新調整下拉菜單

jQuery(document).ready(function(){ 
jQuery("#nav>ul>li").each(function() { 
    pos = jQuery(this).offset(); 
    if(pos.left + 100 > jQuery(window).width()+window.pageXOffset-jQuery(this).width()) { 
    jQuery(this).addClass("nav-shift");} 
}); 
}); 

回答

5

window.pageXOffset屬性是not supported in IE(7和8,至少)。嘗試$(window).offset().left來代替:

jQuery(document).ready(function(){ 
    jQuery("#nav>ul>li").each(function() { 
     pos = jQuery(this).offset(); 
     if(pos.left + 100 > jQuery(window).width()+jQuery(window).offset().left-jQuery(this).width()) { 
     jQuery(this).addClass("nav-shift");} 
    }); 
}); 

更具可讀性,IMO:

jQuery(document).ready(function() { 
    jQuery("#nav > ul > li").each(function() { 
     var $this = jQuery(this), 
      $win = jQuery(window); 

     if ($this.offset().left + 100 > $win.width() + $win.offset().left - $this.width()) { 
      $this.addClass("nav-shift"); 
     } 
    }); 
}); 
+0

Firebug拋出以下錯誤消息與該代碼:jQuery(window).offset()爲空 – GhostPool 2011-06-09 15:43:20

+0

@GhostPool哦,我的壞。使用['$ win.scrollLeft()'](http://api.jquery.com/scrollLeft/)而不是'$ win.offset()。left'。 – jensgram 2011-06-10 06:37:09

3

我用這個代碼:

var absoluteLeft = $(this).offset().left; 
var absoluteTop = $(this).offset().top; 
var absoluteRight = absoluteLeft + $(this).outerWidth(); 
var absoluteBottom = absoluteTop + $(this).outerHeight(); 

var viewportRight = $(window).width() + $(window).scrollLeft(); // scroll left will take into account the position of the horizontal scrollbar 
var viewportBottom = $(window).height() + $(window).scrollTop(); // scroll top will take into account the position of the vertical scrollbar 

if (absoluteRight > viewportRight) { 
    // do whatever to handle horizontal bleeding 
} 
if (absoluteBottom > viewportBottom) { 
    // do whatever to handle vertical bleeding 
} 

沒有在IE瀏覽器的任何問題。該代碼假定絕對定位。