获取元素以单独更改颜色

时间:2015-02-23 12:47:45

标签: javascript html

我希望制作的程序在单独点击每个元素时基本上会改变颜色。我已经让它工作到我可以点击一个页面的位置,这两个元素都可以改变颜色,但我需要它们彼此独立。我该怎么办呢?

document.onload = function()
{
    document.onclick = changeTest("box0", "green");
};

function changeTest(id, color)
{
    var element;
    element = document.getElementById(id);
    element.style.backgroundColor = color;
}

HTML

<!DOCTYPE html>

<html lang="en">
<head>
<title>this will appear on the tab in the browser</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="onclick.js" type="text/javascript"></script>

<style type="text/css">
{
border: 0;
margin:0;
paddig: 0;
}
body
{
font-family:"Times New Roman"; serif;
font-size: 12pt;
}
.box
{
    height: 10em;
    width: 10em;
    margin: 2px;
}
#box0
{
    background-color: yellow;
}
#box1
{
    background-color: red;
}
</style>

</head>
<body>
    <div class="box" id="box0"></div>
    <div class="box" id="box1"></div>
</body>
</html>

3 个答案:

答案 0 :(得分:2)

var box0 = document.getElementById("box0");
var box1 = document.getElementById("box1");

var color = "green";

function changeColor(box, color) {
  box.style.backgroundColor = color;
}

box0.onclick = function() {
  changeColor(this, color);
};

box1.onclick = function() {
  changeColor(this, color);
};
<!DOCTYPE html>
<html>
  <head>
    <title>this will appear on the tab in the browser</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="onclick.js" type="text/javascript"></script>
    <style type="text/css">
      * {
        border: 0;
        margin:0;
        padding: 0;
      }
      
      body {
        font-family:"Times New Roman"; serif;
        font-size: 12pt;
      }
      
      .box
      {
        height: 10em;
        width: 10em;
        margin: 2px;
      }
      
      #box0 {
        background-color: yellow;
      }
      
      #box1 {
        background-color: red;
      }
    </style>
  </head>
  <body>
    <div class="box" id="box0"></div>
    <div class="box" id="box1"></div>
  </body>
</html>

知道你也可以使用addEventListener()方法进行此操作。

答案 1 :(得分:0)

您必须将事件侦听器绑定到各个框。就这么简单。这样的事情(未经测试):

document.getElementById("box0").onclick = changeTest("box0", "green");
document.getElementById("box1").onclick = changeTest("box1", "green");

答案 2 :(得分:0)

我会使用jquery:

html:

<body>
<div class="box" id="box0">box0</div>
<div class="box" id="box1">box1</div>
</body>

和脚本:

 $( "#box0" ).click(function() {
   changeTest("box0", "green");
});

$( "#box1" ).click(function() {
    changeTest("box1", "red");
});

这是一个jsfiddle:

http://jsfiddle.net/o8c8y23x/

好的,没有jquery:

<body>
  <div class="box" id="box0" onclick = "changeTest('box0', 'red');">box0</div>
  <div class="box" id="box1" onclick = "changeTest('box1', 'green');">box1</div>
</body>

的jsfiddle: http://jsfiddle.net/o8c8y23x/2/