当每个div .js-player
的top属性介于10到100之间时,单词#mute
应添加类.active
。以下代码仅在最后.active
div上执行.js-active
的添加。我哪里错了?任何指针都将非常感激。
const players = Array.from(document.querySelectorAll('.js-player')),
mute = document.querySelector('#mute');
window.addEventListener('scroll', function(e) {
players.forEach(function(player) {
let distance = player.getBoundingClientRect().top;
if (10 < distance && distance < 100) {
mute.classList.add('active');
} else {
mute.classList.remove('active');
}
})
});
.js-player {
height: 150px;
width: 200px;
background-color: red;
margin: 8em 2em;
}
#mute {
position: fixed;
top: 10px;
left: 10px;
}
.active {
color: green;
}
.filler {
height: 400px;
}
<div class="js-player"></div>
<div class="js-player"></div>
<div class="js-player"></div>
<div class="filler"></div>
<div id="mute">mute</div>
答案 0 :(得分:1)
我想你想知道为什么只有最后一个-r--r--r--. 1 --- --- 25799 Mar 30 23:38 index.html
确定div是否有.js-player
类?
如果是这样,每次滚动事件发生时,它都会循环播放器,并添加或删除active
类。因此,当它到达最后active
时,如果此最后.js-player
不在距离内,则会删除.js-player
类,如果另一个设置它,并添加它,如果是,它会设置它,即使另一个删除它。
您需要做的是在找到所需距离内的玩家后停止检查,例如:
active
&#13;
const players = Array.from(document.querySelectorAll('.js-player')),
mute = document.querySelector('#mute');
window.addEventListener('scroll', function(e) {
var matched = false;
players.forEach(function(player) {
if (matched) return;
let distance = player.getBoundingClientRect().top;
if (10 < distance && distance < 100) {
mute.classList.add('active');
matched = true;
} else {
mute.classList.remove('active');
}
})
});
&#13;
.js-player {
height: 150px;
width: 200px;
background-color: red;
margin: 8em 2em;
}
#mute {
position: fixed;
top: 10px;
left: 10px;
}
.active {
color: green;
}
.filler {
height: 400px;
}
&#13;
答案 1 :(得分:1)
您在每次迭代时在静音元素上设置active
类,这意味着只有数组的最后一个元素才会重要。
这是一个有效的版本:
const players = Array.from(document.querySelectorAll('.js-player'));
const mute = document.querySelector('#mute');
window.addEventListener('scroll', function(e) {
var active = false;
players.forEach(function (player) {
let distance = player.getBoundingClientRect().top;
if (10 < distance && distance < 100) {
active = true;
}
});
active ? mute.classList.add('active') : mute.classList.remove('active');
});
.js-player {
height: 150px;
width: 200px;
background-color: red;
margin: 8em 2em;
}
#mute {
position: fixed;
top: 10px;
left: 10px;
}
.active {
color: green;
}
.filler {
height: 400px;
}
<div class="js-player"></div>
<div class="js-player"></div>
<div class="js-player"></div>
<div class="filler"></div>
<div id="mute">mute</div>
干杯!