简体   繁体   English

滚动到下一个div时如何更改div的文本

[英]How to change the text that a div has when you scroll to the next div

I've looked on Stack Overflow for a solution however I cannot find one that will work with my project. 我一直在寻找Stack Overflow的解决方案,但是找不到适合我的项目的解决方案。

What i'm trying to do is change the text in the H1 that has the title relevant to the part of the page that the user is on. 我正在尝试做的是更改H1中具有与用户所在页面部分相关的标题的文本。 For instance it could say section 1 then when you scroll down it changes to section two. 例如,它可能会说第1部分,然后当您向下滚动时会更改为第2部分。 I need to do it like this because it's a fixed title that lies underneath a fixed navbar and it should always be there. 我需要这样做,因为它是一个固定的标题,位于固定的导航栏下方,并且应该始终存在。 So to have a solution that would change the contents of it when the next div is at the top of the page would be just what I need. 因此,有一种解决方案可以在下一个div位于页面顶部时更改其内容,这正是我所需要的。

<div id="sticky-anchor"></div>
<div id="sticky" class='a1'><h1 class='titleMusic noSelect'>Arcade Fire</div>

Thats the HTML 多数民众赞成在HTML

function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top) {
    $('#sticky').addClass('stick');
} 
else {
    $('#sticky').removeClass('stick');
}
}

$(function () {
    $(window).scroll(sticky_relocate);
    sticky_relocate();
    });

Thats the Javascript to make the Div 'Sticky' fixed to the top of the page when it gets to the top of the page. 多数民众赞成在Java脚本来使Div'Sticky'固定到页面顶部时,它到达页面的顶部。 I need the text 'Arcade Fire' to change to Section 2 (will do for now) when the div section 2 reaches the top of the page. 当div第2部分到达页面顶部时,我需要将“ Arcade Fire”文本更改为第2部分(现在将这样做)。

you can try something like this in scroll event 您可以在滚动事件中尝试这样的事情

if($(window).scrollTop() > $('section_1').offset().top 
   && $(window).scrollTop() < $('section_1').offset().top + $('section_1').outerHeight(true)
){
   $('#sticky > h1').text('Section 1');
}

Working Demo 工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM