使元素单独更改颜色

Getting elements to change color individually

本文关键字:颜色 单独更 元素      更新时间:2024-03-16

我想制作一个程序,当每个元素被单独点击时,它基本上会改变颜色。我已经做到了可以点击页面,两个元素都可以改变颜色,但我需要它们相互独立。我该怎么做这样的事?

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>

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()方法来执行此操作。

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

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

我会使用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/