通过JS监听浏览器滑动的高度,满足添加就给指定的ID添加或删除class标记
这段代码会监听网页移动的高度,进而给指定的ID添加class标记
核心JS
window.addEventListener("scroll", function (e) {
var t = document.documentElement.scrollTop || document.body.scrollTop;
console.log(t)
if (t < 50) {
document.getElementById("myDIV").classList.remove("mystyle");
}
else {
document.getElementById("myDIV").classList.add("mystyle");
}
});
演示
Npcink
- 0001
- 0001
- 0001
- 0001
- 0001
- 0001
- 0001
- 0001
- 0001
- 0001
- 向下滚动,我会变色哦
- 0001
- 0001
- 0001
- 0001
- 0001
- 0001
- 0001
- 0001
- 0001
- https://www.runoob.com/jsref/prop-element-classlist.html
- https://www.runoob.com/jsref/met-document-getelementsbyclassname.html