为什么更改div内的颜色无效?

时间:2019-05-23 18:05:52

标签: javascript input colors background click

具有id的div是单击,而具有class的div没有单击。通过单击div,我想更改颜色。如果div类中的颜色输入不起作用,如果不在div类中,则它正常工作。我该如何解决?

var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId;

for (var i = 0; i < divCount; i += 1) {
    div[i].onclick = function(e) {
        if (e.target.id) alert(this.id);
		clickedDivId = this.id;
        e.stopPropagation();
    };
}  

function BackgroundColor(){
  var x = document.getElementsByClassName("backgroundcolor")[0].value;
  document.getElementById(clickedDivId).style.backgroundColor = x;
}
#divid{
  width: 450px;
  height: 170px;
  margin: 10px;
  padding: 10px;
  background-color: blue;
}
.divclass{
  width: 450px;
  height: 170px;
  margin: 10px;
  padding: 10px;
  background-color: blue;
}
<div  class="divclass">
     <input type="color" class="backgroundcolor" onchange="BackgroundColor()">
</div>
<div  id="divid"></div>

2 个答案:

答案 0 :(得分:0)

两个div都触发click事件,但是如果单击的div具有id,而第一个没有,则处理程序仅显示警报。

您还使用了实际上应该not be used anymore的旧API(getElementsByTagNamegetElementsByCalssName),并且解决方案比您所做的要简单得多:

let color = document.querySelector(".backgroundcolor"); // Get reference to color input
let targetDiv = document.getElementById("divid"); // Get reference to second div

// Set up click event handler on the document
document.addEventListener("click", function(evt){
  // Check to see if event originated at a div
  if(evt.target.nodeName === "DIV"){
    alert("You clicked a div!"); // Act accordingly
  }
});

// Set up change event on color input
color.addEventListener("change", function(evt){
  // Set color of target div
  targetDiv.style.backgroundColor = color.value;
});
#divid{
  width: 450px;
  height: 170px;
  margin: 10px;
  padding: 10px;
  background-color: blue;
}



.divclass{
  width: 450px;
  height: 170px;
  margin: 10px;
  padding: 10px;
  background-color: blue;
}
<div  class="divclass">
     <input type="color" class="backgroundcolor">
</div>


<div  id="divid">
</div>

答案 1 :(得分:0)

function BackgroundColor(){

  var x = document.getElementById("backgroundcolor1").value;
   
  document.getElementById("clickedDivId").style.backgroundColor = x;
}
#divid{
  width: 450px;
  height: 170px;
  margin: 10px;
  padding: 10px;
  background-color: blue;
}
.divclass{
  width: 450px;
  height: 170px;
  margin: 10px;
  padding: 10px;
  background-color: blue;
}
<div id="clickedDivId" class="divclass">
     <input type="color" id="backgroundcolor1" onclick="BackgroundColor()">
</div>
<div  id="divid"></div>
最好使用ID。我想这就是你想要的。 通过不断改变颜色,背景也会随之改变。