简体   繁体   English

JavaScript在滚动操作上隐藏div元素

[英]JavaScript hide div element on scroll action

I'm using this bit of code to hide a menu bar when users scroll on a page. 当用户在页面上滚动时,我使用这段代码来隐藏菜单栏。 It works fine on Chrome 17.0.963.78 but keeps on flickering in and out on other browsers, namely IE firefox and safari .. 它在Chrome 17.0.963.78上运行良好,但在其他浏览器(即IE firefox和safari ..)上不断闪烁。

$(window).load(function(){
    $(document).scroll(function(){  
        $('#inner_floating').fadeOut();

        var scrollA = $('body').scrollTop();

        setTimeout(function(){
            if(scrollA == $('body').scrollTop()){
                $('#inner_floating').fadeIn();
            }
        }, 100);
    })
});

The problem is that your .scroll function is being called for every pixel (or mousewheel tick) scrolled, so the animations are being run many times consecutively. 问题在于,每滚动一个像素(或鼠标滚轮刻度)都会调用.scroll函数,因此动画要连续运行多次。

Try something like this: 尝试这样的事情:

$(window).load(function(){
    $(document).scroll(function(){  
        if($("#inner_floating:hidden").length == 0) {
            $('#inner_floating').fadeOut();
        }

        var scrollA = $('body').scrollTop();

        setTimeout(function(){
            if(scrollA == $('body').scrollTop() && $("#inner_floating:hidden").length > 0){
                $('#inner_floating').fadeIn();
            }
        }, 100);
    })
});

This way the animation is only happening if necessary. 这样,仅在必要时才发生动画。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM