如何在元素到达某个点后添加类

How to add a class after element reaches some point?

本文关键字:添加 元素      更新时间:2023-09-26

我知道这已经被问了一千次,但我无法解决这个问题。我试图在页面滚动 500px 后显示一个旁白。我对javascript相当陌生,所以我不太确定我在做什么。任何帮助使其工作都会很棒!

$(window).scroll(function() {    
    // find the id with class 'active' and remove it
    $(".work-col-1-2").removeClass("visible");
    // get the amount the window has scrolled
    var scroll = $(window).scrollTop();
    // add the 'active' class to the correct id based on the scroll amount
    if (scroll <= 500) {
        $(".work-col-1-2").addClass("visible");
    }
});
.work-col-1-2 {
    position: fixed;
    right: 6%;
    top: 0;
    width: 25%;
    padding: 1%;
    margin: 0;
    display: inline-block;
    box-sizing: border-box;
    z-index: -1;
    visibility: hidden;
}
.work-col-1-2.visible {
    visibility: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet"/>
<div id="container">
    <div class="work-col-1-2">
        <p>Text here.</p>
    </div>
</div><!-- end of container div-->

可能你有变化

if (scroll <= 500) {
   $(".work-col-1-2").addClass("visible");
}

if (scroll >= 500) {
    $(".work-col-1-2").addClass("visible");
}

您还有 2 个脚本标签。删除一个。

您有两个类,.work-col-1-2 和 .work-col-1-2.visible如果要添加一个名为 visible 的类,则应仅使用名为 visible 的类。

.work-col-1-2 {
position: fixed;
right: 6%;
top: 0;
width: 25%;
padding: 1%;
margin: 0;
display: inline-block;
box-sizing: border-box;
z-index: -1;
visibility: hidden;
}
.visible {
visibility: visible;
}

您的代码很好,但正在查找类名为 .work-col-1-2 的对象,然后添加找不到的可见类。因此,更改类的名称应该可以解决问题。

这是一个工作示例。你所有的选择器都是错误的。您必须使用 # 作为选择器id . class选择器。

$(window).scroll(function() {    
    // find the id with class 'active' and remove it
    $("#work-col-1-2").removeClass("visible");
    // get the amount the window has scrolled
    var scroll = $(window).scrollTop();
    // add the 'active' class to the correct id based on the scroll amount
    if (scroll >= 500) {
        $("#work-col-1-2").addClass("visible");
    }
});
#work-col-1-2 {
    position: fixed;
    right: 6%;
    top: 0;
    width: 25%;
    padding: 1%;
    margin: 0;
    display: inline-block;
    box-sizing: border-box;
    z-index: -1;
    visibility: hidden;
}
#work-col-1-2.visible {
    visibility: visible;
}
#container{height:1000px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet"/>
<div id="container">
    <div id="work-col-1-2">
        <p>Text here.</p>
    </div>
</div><!-- end of container div-->

HTML 中的更改

id="work-col-1-2" to class="work-col-1-2"