当事件发生在另一个元素上时,要删除一个元素上的更改? [英] Remove changes from one element when event occurs on another element?
问题描述
在此程序中,单击任何框都会更改其颜色.但是我希望单击一个框时,它的颜色改变,但是单击另一个框时,它的颜色应该改变,但是第一个框的颜色应该消失(即返回到原始状态).
In this program, clicking any box changes its color. However I want that on clicking one box, its color changes but on clicking the other box, its color should change but color from first box should disappear (ie return back to original state).
从更广泛的角度来看,一旦事件发生在另一个元素上,我如何将一个元素恢复到其原始状态.(就像在css中添加:hover
效果时发生的情况一样,当我们从其中移除鼠标时该元素返回其原始状态)
In a wider perspective, how can i return an element back to its original state once the event occurs on another element. (just like what happens when we add :hover
effects in css, and the element returns to its original state when we remove mouse from it)
编辑-在我的原始项目中,我有很多具有相似点击效果的div.我想要一个通用方法,即一个元素上的事件导致删除所有其他元素上的所有更改.
EDIT - In my original project, I have lots of divs with similar click effects. I want a general method that event on one element leads to removing all changes from all other elements.
var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
div1.addEventListener("click", function() {this.style.backgroundColor="red";});
div2.addEventListener("click", function() {this.style.backgroundColor="red";});
div {
width: 100px;
height: 100px;
margin: 10px;
border: 1px solid black;
}
<html>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>
推荐答案
无论如何都要给DIVS一个类
In any case give the DIVS a class
普通JS
window.onload = function() {
[].map.call(document.querySelectorAll('.toggle'), function(el) {
el.onclick = function() { // attach the handler
[].map.call(document.querySelectorAll('.toggle'), function(el) {
el.classList.remove('active'); // remove from all
});
this.classList.add('active'); // add on current
}
});
}
div {
width: 100px;
height: 100px;
margin: 10px;
border: 1px solid black;
}
.active {
background-color: red
}
<html>
<body>
<div class="toggle" id="div1"></div>
<div class="toggle" id="div2"></div>
</body>
</html>
jQuery ,以备不时之需:
$(function() {
$('.toggle').on("click",function() {
$('.toggle').removeClass("active"); // could add .not(this) here
$(this).addClass("active");
});
});
div {
width: 100px;
height: 100px;
margin: 10px;
border: 1px solid black;
}
.active {
background-color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
<body>
<div class="toggle" id="div1"></div>
<div class="toggle" id="div2"></div>
</body>
</html>
这篇关于当事件发生在另一个元素上时,要删除一个元素上的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!