Reposition drop down menu if near edge of window

偶尔善良 提交于 2019-12-04 11:40:51

The window.pageXOffset property is not supported in IE (7 and 8, at least). Try $(window).offset().left instead:

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");}
    });
});

More readable, 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");
        }
    });
});

I use this code:

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
}

Did not have any problems in IE. The code assumes absolute positioning.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!