javascript 窗口滚动功能不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24959655/
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-10-28 03:40:07  来源:igfitidea点击:

Window Scroll Function Not Working

javascriptjqueryhtml

提问by Aleksi Tappura

I was making a blog, and tried to use $(window).scroll(function(), but something prevents it from working.

我正在制作一个博客,并尝试使用$(window).scroll(function(),但有些东西阻止了它的工作。

I try to add class named scrolledto body when user scrolls down. Any idea which would prevent it working properly? Console doesn't give any error regarding to this.

scrolled当用户向下滚动时,我尝试将名为body 的类添加到正文中。任何想法会阻止它正常工作?控制台对此没有给出任何错误。

JS

JS

$(document).ready(function($) {
    $(window).scroll(function() {    
        var scroll = $(window).scrollTop();

        if (scroll >= 100) {
            $("body").addClass("scrolled");
        } else {
            $("body").removeClass("scrolled");
        }
    });
});

LIVE PREVIEW

实时预览

http://personaii-demo.tumblr.com/

http://personaii-demo.tumblr.com/

回答by Kapilrc

Remove overflow:auto property added to the container. This will work.

删除添加到容器的 overflow:auto 属性。这将起作用。

回答by Ben

Your function takes a $argument, but you're not passing anything in so it gets overwritten, you should do it like this:

您的函数接受一个$参数,但您没有传入任何内容,因此它会被覆盖,您应该这样做:

$(document).ready(function() {
    $(window).scroll(function() {    
        var scroll = $(window).scrollTop();

        if (scroll >= 100) {
            $("body").addClass("scrolled");
        } else {
            $("body").removeClass("scrolled");
        }
    });
});

回答by AlienWebguy

Better JS:

更好的JS:

$(function() {
    $(window).on('scroll', function() {  
        $('body').toggleClass('scrolled', $(this).scrollTop() >= 100);
    });
});

On your website, I see no css associated with .scrolledanywhere even if I apply it via the console.

在您的网站上,.scrolled即使我通过控制台应用它,我也看不到与任何地方相关联的 css 。

回答by mdesdev

Here's a working shorthand solution, fiddle

这是一个有效的速记解决方案,小提琴

$(function() {
  $(window).scroll(function() {    
    var scroll = ($(this).scrollTop() > 100) ? $("body").addClass("scrolled") : $("body").removeClass("scrolled");
  });
});

Also if you're using jQueryUI then you can add a little animation to class changing process with switchClass()e.g.

此外,如果您使用的是 jQueryUI,那么您可以使用switchClass()例如在类更改过程中添加一些动画

var scroll = ($(this).scrollTop() >= 100) ? $("body").switchClass("default","scrolled", 1000) : $("body").switchClass("scrolled","default", 1000);

*Note:Also don't forget to include jQuery/jQueryUI libraries in your document.

*注意:另外不要忘记在您的文档中包含 jQuery/jQueryUI 库。