当使用 Javascript 单击它们时,我将如何使正方形的颜色发生变化



我已经使用事件侦听器将其写出来,但它不起作用,即使单击它们,方块仍然保持黑色。我发现了一些我修复的错别字,但我不确定我使用 getElementsByClassName 是否正确。

.html:

<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
    .square {
        width: 100px;
        height: 100px;
        background-color: #000000;
        margin: 5px;
     }
   </style>
  </head>
 <body>
 <div id="container">
 <div class="square"></div>
 <div class="square"></div>
 <div class="square"></div>
 <div class="square"></div>
 </div>
<script src="js/main.js"></script>
</body>
</html>

和Javascript:

var squares = document.getElementsByClassName('square');
for(var i = 0; i < squares.length; i++) {
squares[0].addEventListener("click", changeColor);
}
function changeColor(event) {
event.style.backgroundColor = randomColor();
}

function randomColor() {
var randomRed = Math.floor(Math.random() * 255);
var randomGreen = Math.floor(Math.random() * 255);
var randomBlue = Math.floor(Math.random() * 255);
//create the string that is the ‘random color’
var randomColor = "rgb("+randomRed+","+randomGreen+","+randomBlue+")";
return randomColor;
}

两个基本问题:

  1. 你的 for 循环有一个硬编码squares[0]何时应该squares[i],所以你多次将处理程序绑定到第一个元素,而不是其他元素。
  2. event对象没有 style 属性。使用 this.style.backgroundColor - 在处理程序中this将引用单击的元素。或使用event.target.style.backgroundColor .

所以像这样:

for(var i = 0; i < squares.length; i++) {
  squares[i].addEventListener("click", changeColor);
}
function changeColor(event) {
  this.style.backgroundColor = randomColor();
}

演示:http://jsfiddle.net/oueLs5dp/

答案很简单。我的以下代码笔更改按预期工作。: http://codepen.io/anon/pen/MwgEdm

首先,你需要修改你的 for 循环,你引用的是索引 0 而不是 i:

    for(var i = 0; i < squares.length; i++) {
        squares[i].addEventListener("click", changeColor);
    }

其次,您需要在更改颜色函数中引用"this",并为事件对象传递 e:

function changeColor(e) {
    this.style.backgroundColor = randomColor();
}

你应该使用 JQuery 来做到这一点,这相对容易。 把这个链接放在你的头标签之间: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 然后将这段代码放在你的javascript中:

$(document).ready(function(){
    $('.square').click(function(){
        $('.square').addClass('green');
    });
});

这是一个演示

使用.addEventListener()您需要更改:

function changeColor(event) {
event.style.backgroundColor = randomColor();
}

function changeColor(){
  // not using Event Object
  this.style.backgroundColor = randomColor();
}

,但让我们面对现实吧.getElementsByClassName()无论如何都不向后兼容。

我建议以下几点:

var doc = document, bod = doc.body;
function E(e){
  return doc.getElementById(e);
}
function inArray(x, a){
  for(var i=0,l=a.length; i<l; i++){
    if(a[i] === x){
      return true;
    }
  }
  return false;
}
function getElementsByClass(className, element){
  var r = false;
  var el = element ? element : doc;
  if(el.getElementsByClassName){
    r = el.getElementsByClassName(className);
  }
  else{
    var all = el.getElementsByTagName('*'), l = all.length;
    if(l > 0){
      r = [];
      for(var i=0; i<l; i++){
        var s = all[i].className.split(/s/);
        if(inArray(className, s))r.push(all[i]);
      }
  }
  return r;
}
function randomColor(context){
  context.style.backgroundColor = 'rgb('+Math.floor(Math.rand()*256)+','+Math.floor(Math.rand()*256)+','+Math.floor(Math.rand()*256)+')';
}

现在就像:

var all = getElementsByClass('square');
for(var i=0,l=all.length; i<l; i++){
  (function(i){ // in case you want to add more array stuff
    all[i].onclick = function(){
      randomColor(this);
      // do more stuff here
    }
  })(i); // end of closure
}

注意:Math.random()返回一个介于 0 和 .9 之间的数字,重复,而不是 1。使用当前的公式,您永远不会得到 255。

最新更新