简体   繁体   English

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

[英]How would I make the color of squares change when they are clicked using Javascript?

I have written it out using an event listener but it does not work and the squares remain black even when they are clicked.我已经使用事件侦听器将它写出来,但它不起作用,即使单击它们,方块仍然是黑色的。 I found a few typos that I fixed but I am not sure whether I was correct in using getElementsByClassName .我发现了一些拼写错误,但我不确定我使用getElementsByClassName是否正确。

html: 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>

and Javascript:和 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;
}

Two basic problems:两个基本问题:

  1. Your for loop has a hardcoded squares[0] when it should be squares[i] , so you're binding the handler to the first element multiple times and not to the others.你的 for 循环有一个硬编码的squares[0]当它应该是squares[i] ,所以你多次将处理程序绑定到第一个元素而不是其他元素。
  2. The event object doesn't have a style property. event对象没有style属性。 Use this.style.backgroundColor - within the handler this will refer to the clicked element.使用this.style.backgroundColor - 在处理程序中, this将引用被点击的元素。 Or use event.target.style.backgroundColor .或者使用event.target.style.backgroundColor

So like this:所以像这样:

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

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

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

The answer is very simple.答案很简单。 My codepen of the below changes working as intended.我对以下更改的代码笔按预期工作。 : http://codepen.io/anon/pen/MwgEdm http : //codepen.io/anon/pen/MwgEdm

First, you need to modify your for loop, you are referencing index 0 instead of i:首先,您需要修改 for 循环,您引用的是索引 0 而不是 i:

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

Second, you need to reference 'this' within your change color function, and pass in e for the event object:其次,您需要在更改颜色函数中引用“this”,并为事件对象传入 e:

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

Using .addEventListener() you would need to change:使用.addEventListener()你需要改变:

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

to

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

, but let's face it .getElementsByClassName() is not backward compatible anyways. ,但让我们面对.getElementsByClassName().getElementsByClassName()无论如何都不向后兼容。

I recommend the following:我推荐以下内容:

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)+')';
}

Now it's like:现在是这样的:

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
}

Note: Math.random() returns a number between 0 and .9 repeating, never 1. You'll never get 255 with your current formula.注意: Math.random()返回一个介于 0 和 .9 之间的重复数字,永远不会是 1。使用当前公式,您永远不会得到 255。

You should use JQuery to do this, it is relatively easy.你应该使用 JQuery 来做到这一点,它相对容易。 put this link between your head tags: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> And then put this code in your javascript:将此链接放在您的 head 标签之间: <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');
    });
});

Here is a demo这是一个演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我需要使用 HTML、CSS 和 Javascript 制作一个按钮,以便在单击按钮时将字体颜色从红色变为红色 - I need to make a button using HTML, CSS, and Javascript to change font color from to red when the button is clicked 单击使用 Javascript 后,如何使形状改变颜色? - How do I make shapes change color after clicked on using Javascript? 单击链接时如何更改跨度颜色 - How can I make a span change color when a link is clicked 我如何让我的分区在点击时改变颜色? - How do I make my divisions to change color when they are clicked? Javascript 单击时如何更改按钮的颜色? - Javascript how to change the color of a button when clicked? 如何使按钮在单击时改变颜色,然后在单击其他按钮时变回其原始颜色? - How to make a button change color when clicked and then change back to its original color when a different button is clicked? 如何使 div 元素移动到随机 position 并在使用 Javascript 事件单击时获得随机颜色? - How do I make a div-element move to a random position and also get random color when it is clicked using Javascript events? 如何更改按钮的颜色,以便在使用jQuery单击按钮时将其更改为另一种颜色? - How do I change the color of a button so that it changes to another color when its clicked using jQuery? 单击时如何使每个元素更改颜色? - How to make each element change color when clicked? 如何更改我单击的特定按钮的此按钮背景颜色? 使用 javascript - How can I change this button background color of the specific button that i have clicked? using javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM