document.getElementById("red").addEventListener("click",function(){
document.getElementById("red").style.backgroundColor = "yellow";
document.getElementById("red").style.color = "#000";
});
document.getElementById("green").addEventListener("click",function(){
document.getElementById("red").style.backgroundColor = "red";
document.getElementById("red").style.color = "#fff";
});
#red{
width:50px;
height:100px;
background-color:red;
color:#fff;
text-align:center;
margin-bottom:10px;
}
#green{
width:100px;
height:50px;
background-color:green;
color:#fff;
text-align:center;
}
<div id="red">div area1</div>
<div id="green"> div area2</div>
是否可以检测到对div区域外部的单击并在that.In上执行操作--上述代码--我尝试更改div#red的颜色:单击div#green(背景:红色;颜色:白色)或外部单击(背景:蓝色;颜色:白色)和自己的单击(背景:黄色;颜色:黑色)。考虑到这个页面上有几个元素,那么如何检测到div#red外部的点击并应用效果呢?
发布于 2016-11-21 01:10:24
您应该使用传递给EventListener函数上的侦听器的事件。事件包含一个目标属性,该属性是接收单击的元素。检查目标id,并对每一种情况执行所需的操作。以下是一个示例:
document.getElementsByTagName("html")[0].addEventListener("click",function(e){
if(e.target.id == "red"){
document.getElementById("red").style.backgroundColor = "yellow";
document.getElementById("red").style.color = "#000";
}
else{
document.getElementById("red").style.backgroundColor = "red";
document.getElementById("red").style.color = "#fff";
}
});
#red{
width:50px;
height:100px;
background-color:red;
color:#fff;
text-align:center;
margin-bottom:10px;
}
#green{
width:100px;
height:50px;
background-color:green;
color:#fff;
text-align:center;
}
<div id="red">div area1</div>
<div id="green"> div area2</div>
发布于 2016-11-21 01:16:07
您可以做的是,即使在文档本身上也添加一个单击,并使用传递给click函数的事件对象来帮助检测正在单击的项目。使用该信息,您可以检测单击是来自元素的内部还是外部。
document.addEventListener("click",function(ev){
if(ev.target.id !== "red" && ev.target.id !== "green"){
document.getElementById("red").style.backgroundColor = "blue";
}
})
这是一个工作的小提琴
https://stackoverflow.com/questions/40716075
复制