根据滚动位置更改div内容

5

我希望能够使用来自其他Stack Exchange帖子中的此代码来寻求一些帮助。下面是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
});

我已经在我的网站上实现了这个功能:http://peterwoyzbun.com/newscroll/scroll.html。当滚动位置到达某一点时,方框中的信息会改变。目前,更改的内容直接来自于div ".post"。也就是说,当用户滚动到给定的".post"时,固定的灰色框加载了".post"中的内容。
我想要做的是让灰色框显示当前用户正在查看的内容的描述。因此,当用户到达div "content1"时,灰色框将显示“content1”的文本描述。也许当到达“content1”时,在灰色框内会出现一个未隐藏的div “description1”?
非常感谢您的帮助。谢谢!

你只需要改变传递给 $('#date').html(...) 的值即可。 - Matt Ball
1个回答

3
在每个包含描述的部分内添加一个隐藏元素,例如:
<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


你能提供一个使用纯JS或TypeScript的示例吗? - Ali Al Amine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接