Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

javascript - Changing div content based on scroll position

I am hoping for some help using this code from another Stack Exchange post. Below is the javascript:

$(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
});

I have implemented it on my own website here: http://peterwoyzbun.com/newscroll/scroll.html. When the scroll position reaches a certain point, the information in the box changes. At the moment, the changing content comes directly from the div ".post". That is, when a user scrolls to a given ".post" the fixed grey box loads what is in ".post".

What I would like to do is have the grey box display a description of what the user is currently seeing. So when the user reaches the div "content1" the grey box displays a text description of "content1". Maybe when "content1" is reached a div "description1" becomes un-hidden within the grey box?

Any help would be greatly appreciated. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add an hidden element inside each section containing the description, for i.e. :

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

then in javascript get the description of the relevant section like this:

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

Jsfiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...