简体   繁体   English

在容器中可见时从元素中删除css类

[英]Removing css class from element when visible in container

I have the following html containers: 我有以下html容器:

<div id="holder">
    <div class="element new">Content</div>
    <div class="element new">Content</div>
    <div class="element new">Content</div>
    <div class="element new">Content</div>
    <div class="element new">Content</div>
    <div class="element new">Content</div>
    <div class="element new">Content</div>
    <div class="element new">Content</div>
    <div class="element new">Content</div>
    <div class="element new">Content</div>
    <div class="element new">Content</div>
    <div class="element new">Content</div>
    <div class="element new">Content</div>
    <div class="element new">Content</div>
    <div class="element new">Content</div>
</div>

The holder container has a max-height of 300px. 支架容器的最大高度为300px。 The element containers have an average height of 50px. 元素容器的平均高度为50px。 The task is now to remove the "new" class from one element container at a time whenever this container hits the top of the holder container. 现在的任务是每当这个容器碰到持有者容器的顶部时,从一个元素容器中删除“new”类。 I have tried several ways with javascript and jquery but none of them are working. 我已经尝试了几种使用javascript和jquery的方法,但它们都没有工作。 Here is my current function 这是我目前的职能

$(document).ready(function() {
    $('#holder').scroll(function() {
        var s = $(".element");
        s.each(function() {
            var pos = s.position();
            var windowpos = $('holder').scrollTop();
            if (windowpos >= pos.top & windowpos <=100) {
                s.removeClass("new");
            }
        });
    });
});

The problem is, that this will remove the class from all of the element containers. 问题是,这将从所有元素容器中删除该类。 Is there a way to remove the class from only the element that hits the top of the holder container? 有没有办法只从撞击持有者容器顶部的元素中删除该类?

If I correctly understand your question, this should solve it: 如果我正确理解你的问题,这应该解决它:

$(document).ready(function() {
    $('#holder').scroll(function() {
        var s = $(".new");
        s.each(function(index, element) {
            var pos = $(element).position();
            var windowpos = $('#holder').scrollTop();
            if (windowpos >= pos.top & windowpos <=100) {
                $(s[0]).removeClass("new");
            }
        });
    });
});

Another problem was, you forgot the # before holder . 另一个问题是,你忘记了# holder

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

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