我想用features__box
类为块的背景着色,但JS不起作用/Chrome无法识别任何错误。
这是 HTML
<div class="features__active features__box">
<h3>Visual Composer</h3>
<p>TheFox comes with the Visual Composer Plugin. You won’t need to code or to remember any shortcodes with our. </p>
</div>
<div class="features__box">
<h3>Responsive</h3>
<p>TheFox comes with the Visual Composer Plugin. You won’t need to code or to remember any shortcodes with our. </p>
</div>
<div class="features__box">
<h3>Retina Ready</h3>
<p>TheFox comes with the Visual Composer Plugin. You won’t need to code or to remember any shortcodes with our. </p>
</div>
这是 JS :
var feature_i = document.querySelectorAll('.features__box');
feature_i.addEventListener('click', function(){
for( var i = 0; i < fearture_i.length; i++) {
feature_i[i].style.backgroundColor = "red";
}
});
默认情况下,每个项目的背景都是白色的。我希望它切换。 请帮忙!
事件侦听器需要位于循环内并附加到每个对象元素。
var feature_i = document.querySelectorAll('.features__box');
for (var i = 0; i < feature_i.length; i++) {
feature_i[i].addEventListener('click', function() {
this.style.backgroundColor = "red"; // where "this" refers to feature_i[i]
});
}
看起来你的 for 循环不正确。循环设置的第二部分中缺少 .length 属性。
for( var i = 0; i < fearture_i; i++) {
feature_i[i].style.backgroundColor = "red";
}
在你写fearture_i的循环中,feature_i的拼写有误。此外,您需要将其更改为feature_i.length。
JQuery有一种更简单的方法。您可以执行以下操作:
$(document).ready(function(){
$(".features__box").click(function(){
$(".features__box").css("background-color", "red");
});
});
编辑为了切换红色chage,函数为:
$(".features__box").click(function(e){
$(".features__box").css("background-color", "white");
var current = e.target;
current.style.background = "red";
});