js样式不起作用

时间:2018-08-28 20:59:54

标签: javascript html5 css3 styles

我想使用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";
    }

});

默认情况下,每个项目的背景都是白色。我希望它切换。 请帮忙!

3 个答案:

答案 0 :(得分:2)

事件侦听器必须位于循环内并附加到每个对象元素。

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]
  });
}

答案 1 :(得分:1)

您的for循环似乎不正确。在循环设置的第二部分中,您缺少.length属性。

for( var i = 0; i < fearture_i; i++) {
    feature_i[i].style.backgroundColor = "red";
}

答案 2 :(得分:1)

您在编写 fearture_i 的循环中 feature_i 的拼写有误。另外,您需要将其更改为 feature_i.length

JQuery有一种更简单的方法。您可以执行以下操作:

$(document).ready(function(){

  $(".features__box").click(function(){
      $(".features__box").css("background-color", "red");
  });

});

修改 为了切换红色,将函数更改为:

$(".features__box").click(function(e){
  $(".features__box").css("background-color", "white");
  var current = e.target;
  current.style.background = "red";
});