jQuery - 分别处理同一个类的多个实例?

时间:2014-06-18 19:09:08

标签: jquery scroll window parallax

目标:

  1. 我尝试创建视差滚动效果。

  2. parallax-container 的实现如下: < div class="parallax slide-1" > < /div >

  3. 当容器滚动到视图时,我需要启动视差效果。

  4. 一旦离开视图,效果就会停止。
  5. 问题:

    到目前为止jQuery工作正常。

    但是:因为我可以在一个页面上多个视差容器(例如,一个位于顶部,一个位于底部),我需要将它们独立处理 jQuery的。

    目前效果是......

    • 1。)一旦第一个视差容器滚动到视图中,就触发每个视差容器
    • 2。)一旦离开视图,就停止每个视差容器。

    所以还不是解决方案。

    思想

    我认为它应该适用于jQuerys .each(),但到目前为止,我还无法真正开始工作。

    当我尝试实现它时,我想我在某处混淆了嵌套函数。

    代码

    这是我目前的代码:

    $(document).ready(function(){
    
    $.fn.is_on_screen = function(){
        var win = $(window);
        var viewport = {
            top : win.scrollTop(),
            left : win.scrollLeft()
        };
        viewport.right = viewport.left + win.width();
        viewport.bottom = viewport.top + win.height();
    
        var bounds = this.offset();
        bounds.right = bounds.left + this.outerWidth();
        bounds.bottom = bounds.top + this.outerHeight();
    
        return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
    };
    
    $(window).scroll(function(){ // Bind window scroll event
        if( $('.parallax').length > 0 ) { // Check if target element exists in DOM
            if( $('.parallax').is_on_screen() ) { // Check if target element is visible on screen after DOM loaded
    
                // ANIMATE PARALLAX EFFECT
                // If Parallax Element is scrolled into view do...
    
                // Variables
                    var speed     = 2.5;
                    var calc      = (-window.pageXOffset / speed) + "px " + (-window.pageYOffset / speed) + "px";
                    var container = $(".parallax");
    
                // Function
                    container.css({backgroundPosition: calc});
    
            } else {
                // ...otherwise do nothing
            }
        }
    });
    
    })
    

1 个答案:

答案 0 :(得分:3)

假设你想要做的滚动是相同的(使用相同的视差方法等),你可以在类上使用.each。例如:

$(window).scroll(function(){ // Bind window scroll event
    $( ".parallax" ).each(function() {
        if( $( this ).is_on_screen() ) { // Check if target element is visible on screen after DOM loaded

            // ANIMATE PARALLAX EFFECT
            // If Parallax Element is scrolled into view do...
            // remember to replace ('.paralax') with (this)

            // Variables
                var speed     = 2.5;
                var calc      = (-window.pageXOffset / speed) + "px " + (-window.pageYOffset / speed) + "px";
                var container = $( this );

            // Function
                container.css({backgroundPosition: calc});

        } else {
            // ...otherwise do nothing
        }
    });
});