为什么更改div内的颜色不起作用? [英] Why change the color inside the div does not work?

查看:207
本文介绍了为什么更改div内的颜色不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Div with the id is clicking, the div with class is not clicking. By clicking div I want to change the color. If the color input within the div class is not working, if it is out of div class it works normally. How do I fix this?

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>

推荐答案

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.我想这就是你想要的. 通过不断改变颜色,背景也会改变.

It is better to use ID. I guess this is what you want. By keep changing the color the background will change as well.

这篇关于为什么更改div内的颜色不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆