【问题标题】:IE7: can't get menu to stick to top of pageIE7:无法让菜单粘在页面顶部
【发布时间】:2012-01-02 08:58:29
【问题描述】:

在这里演示:

http://jsfiddle.net/auMd5/

我希望蓝色菜单栏在您滚动过去时停留在页面顶部,然后在您向上滚动时快速回到其原始位置。在我测试过的所有其他浏览器中,让 jQuery 有条件地将菜单的 positionrelative 切换到 fixed 有效。但它在 IE7 中不起作用。

为了测试,我尝试删除所有 JavaScript 并将 CSS 中的 position 设置为 fixed。这在 IE7 中看起来应该如此。

还要测试,我已经让条件if ($('table#menu').position().top + 10 <= $(window).scrollTop()) 触发警报。它可以工作,这意味着 IE7 可以识别该事件。

所以我想要的 CSS 是静态工作的,而 JavaScript 条件是工作的。关于问题可能是什么的任何想法?

【问题讨论】:

    标签: javascript jquery css internet-explorer internet-explorer-7


    【解决方案1】:

    似乎如果您.remove() DOM 元素,更改它的 CSS,然后将其添加回 DOM,它在 IE 7 中可以正常工作:

    $(function() {
    
        //cache all the objects we will need and get the initial top offset for the #menu
        var $window  = $(window),
            $menu    = $('#menu'),
            menuTop  = $menu.offset().top,
            $midWrap = $('#mid-wrap');
    
        $window.scroll(function() {
    
            //cache a copy of the #menu object and get it's CSS position property
            var $tmp      = $menu,
                position  = $tmp.css('position'),
                windowTop = $window.scrollTop();
    
            $menu.remove();
    
            //if the position is not already set to fixed and the #menu element is above the fold
            if (position != 'fixed' && menuTop <= windowTop) {
    
                //remove the current #menu element from the DOM
                $menu.remove();
    
                //set the position property of the new #menu element
                $tmp.css('position', 'fixed');
    
                //re-insert the #menu item into the dom
                $midWrap.prepend($tmp);
                $menu = $tmp;
    
            //if the position is not already set to relative and the #menu element's offset is greater than how far the user has scrolled down
            } else if (position != 'relative' && menuTop > windowTop) {
    
                //remove the current #menu element from the DOM
                $menu.remove();
    
                //set the position property of the new #menu element
                $tmp.css('position', 'relative');
    
                //re-insert the #menu item into the dom
                $midWrap.prepend($tmp);
                $menu = $tmp;
            }
        });
    });
    

    这是一个演示:http://jsfiddle.net/auMd5/5/

    【讨论】:

    • 嗯。我在 IE7 中尝试了你的演示(实际上,如果重要的话,IE8 兼容模式),菜单栏就消失了,没有回来。
    • @user460847 我必须进行一些更改,现在查看演示(对我有用,我对其进行了一些优化):jsfiddle.net/auMd5/4
    • 谢谢,它有效!一旦我睡了,我会试着真正理解它:)
    猜你喜欢
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多