【发布时间】:2018-06-25 09:05:00
【问题描述】:
我在滚动标题上做了 2 个固定:
var header = document.getElementsByClassName("header");
function headerChange(){
if(header[1].getBoundingClientRect().top <= 70){
header[0].classList.add("fixed-removal");
} else {
header[0].classList.remove("fixed-removal");
}
if(header[0].getBoundingClientRect().top <= -70){
header[1].classList.add("fixed-add");
} else {
header[1].classList.remove("fixed-add");
}
}
document.addEventListener("scroll", headerChange);
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.header {
width: 100%;
height: 70px;
font-family: Arial, sans-serif;
font-size: 2em;
}
.content {
width: 100%;
height: 100%;
background-color: yellow;}
.header:nth-of-type(1){
position: fixed;
background-color: dodgerblue;
}
.header:nth-of-type(2){
background-color: red;
}
.fixed-removal {
position: absolute !important;
bottom: 0;
}
.fixed-add {
position: fixed;
top: 0;
}
.content:nth-of-type(2){
margin-bottom: 200px;
}
<header class="header">HEADER 1</header>
<div class="content"></div>
<header class="header">HEADER 2</header>
<div class="content"></div>
一切正常……这就是问题所在。现在我只有 2 个滚动固定标题,但是当我有更多标题时,JavaScript 是否会继续在滚动时触发 if/else 语句?我担心CPU性能,这就是原因。
我不希望它无缘无故地运行,只是为了限制性能。尤其是 else 声明。
请不要 jQuery 答案
【问题讨论】:
标签: javascript html css scroll