javascript - jQuery:添加类并从所有 sibling 中删除

标签 javascript jquery html css

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

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

我有一个代码笔演示: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') 到最后一张幻灯片以滚动到顶部。

我根据你的CodePen做了一个例子,希望对你有帮助:

注意:如果将 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>

关于javascript - jQuery:添加类并从所有 sibling 中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35327392/

相关文章:

javascript - 添加新的全日历事件后添加类名

javascript - window.sidebar.addPanel 不再在 Firefox 上运行

javascript - 如何使用 jQuery 添加通用页眉页脚

css - css代码行的解释

javascript - 如何禁用单页应用程序某些页面的后退按钮

javascript - 将 Blobstore Python API 与 ajax 结合使用

javascript - 具有启动逻辑的延迟筛选算法

同一页面上的 jQuery 幻灯片在单击时一起移动

jquery - 根据标题用 jQuery 隐藏 anchor href

html - 如何为 IE7 修复站点