在不同的计算器上进行的计算与我编写的脚本不同

时间:2020-05-14 16:04:50

标签: javascript css class settimeout add

在单击div click时,div three的背景色应更改,然后在一秒钟后更改。我下面有添加类的代码,但是样式没有显示在页面上。

let temp = document.querySelector('.three');
document.querySelector('.clickhere').addEventListener('click', () => {
  temp.classList.add('.select');
  console.log(temp);
  setTimeout(function() {
    temp.classList.remove('.select');
    console.log(temp);
  }, 1000);
});
.one {
  background-color: red;
}

.two {
  background-color: green;
}

.three {
  background-color: blue;
}

.select {
  background-color: black;
}

.clickhere {
  background-color: yellow;
}
<div class="one">
  ONE
</div>
<div class="two">
  TWO
</div>
<div class="three">
  THREE
</div>
<div class="clickhere">
  CLICK HERE
</div>

2 个答案:

答案 0 :(得分:1)

更新了您的代码段,我只需要将.select替换为select

仅在使用jQuery选择css类之前使用句号很重要,在添加新类并删除它时,您应该像在div标记内那样写它的名称。

编辑:我刚刚看到问题已经在评论中得到了解答,感谢@maazadeeb! :)

let temp = document.querySelector('.three');
document.querySelector('.clickhere').addEventListener('click', () => {
  temp.classList.add('select');
  console.log(temp);
  setTimeout(function() {
    temp.classList.remove('select');
    console.log(temp);
  }, 1000);
});
.one {
  background-color: red;
}

.two {
  background-color: green;
}

.three {
  background-color: blue;
}

.select {
  background-color: black !important;
}

.clickhere {
  background-color: yellow;
}
<div class="one">
  ONE
</div>
<div class="two">
  TWO
</div>
<div class="three">
  THREE
</div>
<div class="clickhere">
  CLICK HERE
</div>

答案 1 :(得分:0)

temp.classList.add(' .select ');应该更新为temp.classList.add(' select ');

let temp = document.querySelector('.three');
document.querySelector('.clickhere').addEventListener('click', () => {
    temp.classList.add('select');
    setTimeout(function () {
        temp.classList.remove('select');
    }, 1000);
});
.one {
  background-color: red;
}

.two {
  background-color: green;
}

.three {
  background-color: blue;
}

.select {
  background-color: black;
}

.clickhere {
  background-color: yellow;
}

.select {
  background: coral;
}
<div class="one">
    ONE
</div>
<div class="two">
    TWO
</div>
<div class="three">
    THREE
</div>
<div class="clickhere">
    CLICK HERE
</div>