jQuery:addClass 并从所有同级中删除

jQuery: addClass and remove from all siblings

本文关键字:删除 addClass jQuery      更新时间:2023-09-26

我设置了一个函数,当每个元素到达浏览器顶部时,它会添加一个active类,然后修复它,以便下一个元素将滚动到它的顶部。它在Chrome中运行良好,但是当我在Safari中进行测试时,它似乎真的很跳跃。

我可以在代码中看到$('.content').removeClass();干扰了addClass函数,我不知何故需要编写一个函数,当scroller-slide到达顶部时添加类,但将其从所有兄弟姐妹的孩子中删除,有没有一种干净的方法来写这个?

我有一个代码笔演示:http://codepen.io/anon/pen/RrqRzR

我的jQuery标记如下:

$(document).ready(function () {
    $('.scroller-slide:first-child').children('.content').addClass('active');
    $(window).on('scroll', function() {
        var scrolled = $(this).scrollTop();
        $('.scroller-slide').filter(function() {
          $('.content').removeClass('active');   
          return scrolled >= $(this).offset().top-0;
        }).children('.content').addClass('active');
    });
});

对此的任何建议将不胜感激!

为了提高性能,请尝试尽量减少 scroll 事件中的函数调用次数。因此,将幻灯片的顶部偏移值存储在全局数组中,这样就不必在滚动的每个像素上计算它们。调整大小时更新这些值。

在滚动事件中,检查最后一张幻灯片是否滚动到窗口顶部上方(使用全局数组)。然后检查此幻灯片是否已具有active类。如果是这样,请保持一切原样。如果没有,请从幻灯片中删除所有active类(仅 1 个元素)。然后addClass('active')到最后一张幻灯片以滚动到顶部上方。

我根据您的代码笔做了一个例子,希望对您有所帮助:

注意:如果将active类设置为 .scroller-slide 元素本身,则可以减少函数调用。(因为您不必遍历和检查子元素.content。当然,您必须为此调整JS和CSS。

// Set global top offset values
var slide_offsets;
var last_slide;
  $(document).ready(function () {
        Resize();
    });
    
    $(window).load(function () {
        Resize();
    });
    //Every resize of window
    $(window).resize(function () {
        Resize();
    });
    //Dynamically assign height
    function Resize() {
        // Handler for .ready() called.
        var windowHeight = $(window).height(),
            finalHeight = windowHeight + 'px';
        $('.fullscreen').css('min-height', finalHeight);
        // Reset offset values
        slide_offsets = null;
        slide_offsets = [];
      
        // Update offset values
        $('.scroller-slide').each(function(i, el){
          slide_offsets[ i ] = $(this).offset().top-0;
        });
    }
    //Fix Elements on Scroll
	$(document).ready(function () {
		
		$('.scroller-slide').eq(0).find('> .content').addClass('active');
		
		$(window).on('scroll', function() {
		    var scrolled = $(this).scrollTop();
            // Reset last_slide
            last_slide = 0;
          
            // Get last slide to scroll above top
            $.each(slide_offsets, function(i,v){
                if ( v <= scrolled ) {
                    last_slide = i;
                }
            });
      
            // Check if any slide is above top and that last slide is not yet set to class 'active'
            if ( last_slide >= 0 && 
                ! $('.scroller-slide').eq( last_slide ).children('.content').hasClass('active') ) {
         
                // Remove all 'active' classes from slide .content's (which will be 1 item)
                $('.scroller-slide > .content.active').removeClass('active');
                // Set class 'active' to last slide to scroll above top
                $('.scroller-slide').eq( last_slide ).find('>.content').addClass('active');
            }
        });
		
	});
/*
RESETS ------------------------
*/ 
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {margin: 0;padding: 0;border: 0;outline: 0;font-size: 100%;vertical-align: ;background: transparent;}
/*
RESETS END --------------------
*/
.scroller-slide {
	position: relative;
	width: 100%;
}
.scroller-slide .content {
	position: absolute;
	width: 100%; height: 100%;
	top: 0; left: 0;
}
.scroller-slide .content.image-background {
	background: no-repeat 50% 50%;
	-webkit-background-size: cover;
	-moz-background-size: cover;
	-o-background-size: cover;
	background-size: cover;
}
.scroller-slide .content .inner-scroller-content {
	position: absolute;
	width: 100%; height: 100%;
	top: 0; left: 0;
	opacity: 0;
	-webkit-transition: opacity 300ms ease-in-out;
    -moz-transition: opacity 300ms ease-in-out;
    -ms-transition: opacity 300ms ease-in-out;
    -o-transition: opacity 300ms ease-in-out;
    transition: opacity 300ms ease-in-out;
}
.scroller-slide .active {
	position: fixed !important;
	top: 0; left: 0;
}
.scroller-slide .active .inner-scroller-content {
	opacity: 1 !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scroller-slide fullscreen">
	    <div class="content colour-background" style="background-color: #939597;">
        <div class="inner-scroller-content">
          Slide 01
        </div>
	    </div>
	</div>
	<div class="scroller-slide fullscreen">
	    <div class="content colour-background" style="background-color: #f7a986;">
        <div class="inner-scroller-content">
          Slide 02
        </div>
	    </div>
	</div>
	<div class="scroller-slide fullscreen">
	    <div class="content colour-background" style="background-color: #d2b63a;">
        <div class="inner-scroller-content">
          Slide 03
        </div>
	    </div>
	</div>

有一种非常小的方法可以达到这种效果,只需使用 jquery 每个函数添加和删除类即可。 首先从每个部分的包装器开始,然后将活动类添加和删除到此部分包装器中。 然后修复节包装器内部的部分。

这是小提

琴小提琴

$(window).on( "scroll", function() {
    $( ".section-wrapper" ).each(function() {
        if ( $(window).scrollTop() >= $(this).offset().top) {
            $(this).addClass("active");
        }else{
              $(this).removeClass("active");
        }
    });
});

然后是 css

.section-wrapper{
  height: 100vh;
}
.section{
  height: 100vh;
  width: 100%;
  position: relative;
}
.section-wrapper.active .section{
  position: fixed;
  top: 0;
  left: 0;
}

和 HTML

<div class="section-wrapper">
  <div class="section" style="background: #111;">Section 1</div>
</div>
<div class="section-wrapper">
  <div class="section" style="background: #222;">Section 2</div>
</div>
<div class="section-wrapper">
  <div class="section" style="background: #333;">Section 3</div>
</div>
<div class="section-wrapper">
  <div class="section" style="background: #444;">Section 4</div>
</div>