1 回答

TA貢獻(xiàn)1828條經(jīng)驗 獲得超6個贊
你不應(yīng)該使用offsetHeight
,offsetTop
而是使用。在您的示例中Section-1
并且Section-2
具有相似的高度,因此您不會面對任何東西..如果您的Section-2
高度大于/小于Section-1
它,它將無法按預(yù)期工作......
在下面的兩個示例中,我將#Section-2
元素的高度減少到500px
而不是1000px
.
看到這個或看到下面的片段:
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);
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
#header {
background: #ccc;
padding: 24px;
position: fixed;
width: 100%;
}
#header.white {
background: tomato;
}
#section-1 {
background: #fff;
height: 1000px;
}
#section-2 {
background: #000;
height: 500px;
}
#section-3 {
background: yellow;
height: 1000px;
}
<header id="header">
<h1>Logo</h1>
<p>(Section-2 height=500px and checking with <strong>offsetHeight</strong>)</p>
</header>
<div id="section-1">
Section 1
</div>
<div id="section-2">
Section 2
</div>
<div id="section-3">
Section 3
</div>
你應(yīng)該使用offsetTop
來使條件..
看到這個或看到下面的片段:
var height = document.getElementById('section-2').offsetTop;
function logoChanger() {
if(this.scrollY > height) {
document.getElementById('header').classList.add('white');
} else {
document.getElementById('header').classList.remove('white');
}
}
window.addEventListener('scroll', logoChanger);
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
#header {
background: #ccc;
padding: 24px;
position: fixed;
width: 100%;
}
#header.white {
background: tomato;
}
#section-1 {
background: #fff;
height: 1000px;
}
#section-2 {
background: #000;
height: 500px;
}
#section-3 {
background: yellow;
height: 1000px;
}
<header id="header">
<h1>Logo</h1>
<p>(Section-2 height=500px and checking with <strong>offsetTop</strong>)</p>
</header>
<div id="section-1">
Section 1
</div>
<div id="section-2">
Section 2
</div>
<div id="section-3">
Section 3
</div>
添加回答
舉報