【问题标题】:How would I make the color of squares change when they are clicked using Javascript?使用Javascript单击正方形时,如何使正方形的颜色发生变化?
【发布时间】:2015-04-19 03:57:29
【问题描述】:

我已经使用事件侦听器将其写出来,但它不起作用,即使单击它们,方块仍保持黑色。我发现了一些拼写错误,但我不确定我使用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;
}

【问题讨论】:

    标签: javascript html event-handling dom-events onclicklistener


    【解决方案1】:

    两个基本问题:

    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/

    【讨论】:

      【解决方案2】:

      答案很简单。我对以下更改的代码笔按预期工作。 :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();
      }
      

      【讨论】:

      • 抱歉,当我写这篇文章并设置 codepen 时,我没有重新加载页面并看到 nnnnnn 的回答。他比我先回答了一点,请标记他为正确。
      【解决方案3】:

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

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

      这是demo

      【讨论】:

      • “你应该使用 jQuery” - 不,你可以选择使用 jQuery。这里没有“应该”。没有 jQuery 也很简单。
      • @nnnnnn 见仁见智
      • 我喜欢 jQuery。我用它。我推荐它。但我仍然说“应该”夸大了它,特别是当 OP 没有用它标记问题时。尤其是当问题中的代码只需要更改六个字符即可完美运行时。这在 vanilla JS 中实现并不难。
      • 这是一个纯 JavaScript 问题 Joshua。说“使用框架/库 xyz”对试图学习和理解原始 JS/HTML 的人没有帮助。
      【解决方案4】:

      使用.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 和 0.9 之间重复的数字,而不是 1。使用当前公式,您永远不会得到 255。

      【讨论】:

      • 如果一个元素分配了多个类,您的自定义 getElementsByClass() 函数是否有效?
      猜你喜欢
      • 2018-02-11
      • 1970-01-01
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      • 2013-01-03
      • 1970-01-01
      • 2015-04-11
      • 1970-01-01
      相关资源
      最近更新 更多