如何根据 div offsetHeight 更改标题的背景颜色?

当我通过原始 div 以外的 div 时,我试图更改标题的颜色,但我没有得到它。如何向 window.addEventListener 添加另一个函数?是这样吗?


爪哇脚本


var height = document.getElementById('section-2').offsetHeight;


function logoChanger() {

  if(this.scrollY > height) {

    document.getElementById('header').classList.add('white');

  } else {

    document.getElementById('header').classList.remove('white');

  }

}


window.addEventListener('scroll', logoChanger);


喵喵时光机
浏览 180回答 1
1回答

30秒到达战场

你不应该使用offsetHeight,offsetTop而是使用。在您的示例中Section-1并且Section-2具有相似的高度,因此您不会面对任何东西..如果您的Section-2高度大于/小于Section-1它,它将无法按预期工作......在下面的两个示例中,我将#Section-2元素的高度减少到500px而不是1000px.看到这个或看到下面的片段:var height = document.getElementById('section-2').offsetHeight;function logoChanger() {&nbsp; if(this.scrollY > height) {&nbsp; &nbsp; document.getElementById('header').classList.add('white');&nbsp; } else {&nbsp; &nbsp; document.getElementById('header').classList.remove('white');&nbsp; }}window.addEventListener('scroll', logoChanger);* {&nbsp; box-sizing: border-box;&nbsp; margin: 0;&nbsp; padding: 0;}#header {&nbsp; background: #ccc;&nbsp; padding: 24px;&nbsp; position: fixed;&nbsp; width: 100%;&nbsp;&nbsp;}&nbsp; #header.white {&nbsp; &nbsp; background: tomato;&nbsp; }#section-1 {&nbsp; background: #fff;&nbsp; height: 1000px;}#section-2 {&nbsp; background: #000;&nbsp; height: 500px;}#section-3 {&nbsp; background: yellow;&nbsp; height: 1000px;}<header id="header">&nbsp; <h1>Logo</h1>&nbsp; <p>(Section-2 height=500px and checking with <strong>offsetHeight</strong>)</p></header><div id="section-1">&nbsp; Section 1</div><div id="section-2">&nbsp; Section 2</div><div id="section-3">&nbsp; Section 3</div>你应该使用offsetTop来使条件..看到这个或看到下面的片段:var height = document.getElementById('section-2').offsetTop;function logoChanger() {&nbsp; if(this.scrollY > height) {&nbsp; &nbsp; document.getElementById('header').classList.add('white');&nbsp; } else {&nbsp; &nbsp; document.getElementById('header').classList.remove('white');&nbsp; }}window.addEventListener('scroll', logoChanger);* {&nbsp; box-sizing: border-box;&nbsp; margin: 0;&nbsp; padding: 0;}#header {&nbsp; background: #ccc;&nbsp; padding: 24px;&nbsp; position: fixed;&nbsp; width: 100%;&nbsp;&nbsp;}#header.white {&nbsp; &nbsp; background: tomato;&nbsp; }#section-1 {&nbsp; background: #fff;&nbsp; height: 1000px;}#section-2 {&nbsp; background: #000;&nbsp; height: 500px;}#section-3 {&nbsp; background: yellow;&nbsp; height: 1000px;}<header id="header">&nbsp; <h1>Logo</h1>&nbsp; <p>(Section-2 height=500px and checking with <strong>offsetTop</strong>)</p></header><div id="section-1">&nbsp; Section 1</div><div id="section-2">&nbsp; Section 2</div><div id="section-3">&nbsp; Section 3</div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript