javascript 当用户滚动到元素上方 50 像素时向元素添加类?

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

Add class to an element when user scrolls to 50px above it?

javascriptjqueryhtmlcss

提问by caustic

Does anyone know how I can achieve the following with jQuery:

有谁知道我如何使用 jQuery 实现以下目标:

I want to add a class (.fixed) to an element (#content) when a user reaches 50px above #content. And then, when the user scrolls up 50px above #content, I want to remove the class.

当用户到达#content 上方 50px 时,我想向元素 (#content) 添加一个类 (.fixed)。然后,当用户向上滚动 #content 上方 50px 时,我想删除该类。

How can I do this with as little script as possible?

我怎样才能用尽可能少的脚本来做到这一点?

<div id="header">
</div>

<div id="content">
</div>

<div id="content-2">
</div>

FIDDLE

小提琴

回答by g_marchildon

If I understand correctly, this should do the trick.

如果我理解正确,这应该可以解决问题。

$(function(){
    $(document).scroll(function(){
        if($(this).scrollTop() >= $('#content').offset().top - 50) {
            $("#content").css("background","red");
        } else {
            $("#content").css("background","orange");
        }
    });
});

Basically, it check the current position of the user's scroll and compare it to the position of the div minus 50 pixel.

基本上,它检查用户滚动的当前位置,并将其与 div 的位置减去 50 像素进行比较。

If you just past this code in your document, it should work properly.

如果您只是在文档中粘贴了此代码,它应该可以正常工作。

回答by Logz

Try this,

试试这个,

$(window).scroll(function() {

    if ($(this).scrollTop() > 50){  
        $('#content').addClass("content_fixed");
    }
    else{
        $('#content').removeClass("content_fixed");
    }
});

Demo : http://jsfiddle.net/UI_Designer/8j0a1Lkk/1/

演示:http: //jsfiddle.net/UI_Designer/8j0a1Lkk/1/

回答by Leuven Wang

You can use the jquery plugin waypoint (http://imakewebthings.com/waypoints/) to detect when the user has scrolled to the area and then use the javascript .innerhtml function to change the html code. The one problem with this method is that you have to have another element that surrounds your main element ONLY.

您可以使用 jquery 插件 waypoint ( http://imakewebthings.com/waypoints/) 来检测用户何时滚动到该区域,然后使用 javascript .innerhtml 函数更改 html 代码。这种方法的一个问题是你必须有另一个元素只围绕你的主要元素。