jQuery 向下滚动 1000px 后更改 CSS 类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12470645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:43:18  来源:igfitidea点击:

Change CSS class after scrolling 1000px down

jquerycssscrollfixed

提问by taylor

I want a fixed menu to appear in the left column of my site once the user scrolls 1000px down, but am not very experienced with jQuery/JS. I thought something like this would work but it isn't doing anything:

一旦用户向下滚动 1000 像素,我希望在我网站的左栏中显示一个固定菜单,但我对 jQuery/JS 的经验不是很丰富。我认为这样的事情会起作用,但它没有做任何事情:

HTML:

HTML:

<div id="menu">[MENU_WILL_GO_HERE]</div>

STYLE:

风格:

#menu{display:none;}?

JQ:

江青:

var fixed = false;
 ?$(document).scroll(function() {
    if( $(this).scrollTop() > 100 ) {
        if( !fixed ) {
           fixed = true;
           $('#menu').css({position:'fixed', display:'block'});
        }
        } else {
           if( fixed ) {
               fixed = false;
               $('#menu').css({display:'none'});
        } 
    } 
});?

Q:

问:

Is there a reason this doesn't work? The code is an example on http://jsfiddle.net/roXon/psvn9/1/, and even when I copy/paste that example exactly as it is into a blank html page, with a link of the latest jquery library, it still doesn't work like it does on that jsfiddle page. What could I be overlooking?

有没有理由这不起作用?该代码是http://jsfiddle.net/roXon/psvn9/1/上的示例,即使我将该示例完全按原样复制/粘贴到空白 html 页面中,并带有最新 jquery 库的链接,它仍然不能像在那个 jsfiddle 页面上那样工作。我可以忽略什么?

回答by AlienWebguy

Your braces are wrong in your example, but regardless, you can simplify your code:

您的示例中的大括号是错误的,但无论如何,您可以简化代码:

CSS:

CSS:

#menu {
    display : none;
    position : fixed;
}

JS:

JS

 $(document).scroll(function() {
    $('#menu').toggle($(this).scrollTop()>1000)
 });? 

Demo: http://jsfiddle.net/elclanrs/h3qyV/1/

演示http: //jsfiddle.net/elclanrs/h3qyV/1/

回答by Gautam3164

Edit like this

像这样编辑

if( $(this).scrollTop() > 1000 )

you are looking for 1000px scroll,but it appears 100px due to this,from your code

您正在寻找 1000px 滚动,但由于这个原因,从您的代码中它显示为 100px