2017-07-24 72 views
1

我有一个具有相同类的多个外部和内部div的HTML文档。我也有一个JQuery的功能,使内部股东向下滚动页面。但是,我只能得到第一个内部div元素的功能,而不是其他功能。这里是我的HTML:如何将多个div彼此链接并同时滚动它们?

<div class='parent'>  
    <div class='child'> 
     Val1 
    </div> 
</div> 
<div class='parent'>  
    <div class='child'> 
     Val2 
    </div> 
</div> 
<div class='parent'>  
    <div class='child'> 
     Val3 
    </div> 
</div> 

我的CSS:

.child { 
    background:#ace; 
    text-align: center; 
    line-height: 40px; 
    width:100px; 
    height: 40px; 
    position:absolute; top:0; left:0; 
} 

.parent { 
    position:relative; 
    background: gray; 
    margin-bottom: 1px; 
    width: 100px; 
    height: 1000px; 
} 

body{ 
    height: 10000px; 
} 

而且我的JQuery:

var parent = $('.parent'); 
var child = $('.child'); 
var pheight = parent.height(); 
var cheight = child.height(); 


$.fn.followTo = function (pos) { 
    var $this = this, 
     $window = $(window); 

    $window.scroll(function(e){ 
     if (((child.position().top + cheight) >= pheight) && ($window.scrollTop() >= (pheight + cheight))){ 
      $this.css({ 
       position: 'absolute', 
       top: pos 
      }); 
     } else { 
      $this.css({ 
       position: 'fixed', 
       top: 0 
      }); 
     } 
    }); 
}; 

$('.child').followTo(pheight - cheight); 

这里有一个的jsfiddle:http://jsfiddle.net/Tgm6Y/11879/

基本上我希望每个 “VAL1” 的,“Val2”和“Val3”divs按照“Val1”目前的方式向下滚动页面,但我不确定正确的方式在JQuery中是这样做的。

+0

您正在使用的ID,而不是类。每个文档只能应用一次ID。切换到课程。 – sean

+0

谢谢,我更新了它。当我尝试使用类时,我一定错过了一些简单的语法。 但是,这仍然不能提供所需的功能,正如您可以在更新的JSFiddle中看到的那样。我如何正确调用这个函数来处理所有的类? – Kaisermania

回答

0

您正在使用child.position().top,但child是一个收集您的元素
相反,你宁愿要检查每个元素的位置。

这里有一个稍微不同的和更简单的方法

var $parent = $(".parent").each(function() { 
 
    this._child = $(this).find(".child"); 
 
}); 
 

 
function fixpos() { 
 
    $parent.each(function(){ 
 
    var br = this.getBoundingClientRect(); 
 
    $(this._child).toggleClass("sticky", br.top<0 && br.bottom>0); 
 
    }); 
 
} 
 

 
fixpos(); 
 
$(window).on("load scroll", fixpos);
/*QuickReset*/ *{box-sizing: border-box;margin:0;}html,body{height:100%;font:16px/1 sans-serif;} 
 

 
.parent { 
 
    position: relative; 
 
    background: gray; 
 
    margin-bottom: 1px; 
 
    height: 1000px; 
 
    padding-top: 40px; /* ADD THIS - Height of heading */ 
 
} 
 

 
.child { 
 
    background: #ace; 
 
    text-align: center; 
 
    line-height: 40px; 
 
    width: 100%; 
 
    height: 40px; 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
} 
 

 
.child.sticky { /* ADD THIS */ 
 
    position: fixed; 
 
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script> 
 

 
<div class='parent'> 
 
    <div class='child'>Val1</div>1 
 
</div> 
 
<div class='parent'> 
 
    <div class='child'>Val2</div>2 
 
</div> 
 
<div class='parent'> 
 
    <div class='child'>Val3</div>3 
 
</div>

+1

谢谢,这是完美的! – Kaisermania