2013-04-25 85 views
4

我希望能夠使用另一個Stack Exchange帖子中的this代碼提供一些幫助。以下是javascript:根據滾動位置更改div內容

$(window).on("scroll resize", function(){ 
    var pos=$('#date').offset(); 
    $('.post').each(function(){ 
     if(pos.top >= $(this).offset().top && pos.top <= $(this).next().offset().top) 
     { 
      $('#date').html($(this).html()); //or any other way you want to get the date 
      return; //break the loop 
     } 
    }); 
}); 

$(document).ready(function(){ 
    $(window).trigger('scroll'); // init the value 
}); 

我已在我自己的網站上實現它:http://peterwoyzbun.com/newscroll/scroll.html。當滾動位置到達某個點時,框中的信息會發生變化。目前,不斷變化的內容直接來自div「.post」。也就是說,當用戶滾動到給定的「.post」時,固定的灰色框會加載「.post」中的內容。

我想要做的是讓灰色框顯示用戶當前所看到的內容。因此,當用戶到達div「content1」時,灰色框會顯示「content1」的文本說明。也許當「content1」達到某個div時,「description1」在灰色框中變爲未隱藏?

任何幫助將不勝感激。謝謝!

+0

你只需要改變傳遞給'$('#date')。html(...)'的值。 – 2013-04-25 00:15:19

回答

2

添加一個隱藏的元素包含描述每個部分內部,即:

<div id="content1"> 
<p class="description" style="display: none;">content1 description</p> 
.... 
</div> 

然後在JavaScript中獲得相關部分的這樣的描述:

if(pos.top >= $(this).offset().top && pos.top <= $(this).next().offset().top) 
     { 
      $('#date').html($(this).find('.description').text()); 
      return; 
     } 

Jsfiddle

+0

非常感謝! – Malthus 2013-05-05 22:25:46