使用 onmouseover 更改正方形的颜色

我开始学习 js,现在我列出了练习清单。在此列表中,我需要制作一个按钮,每次单击时,屏幕上都会出现一个新的红色方块,并且我总是将鼠标移到任何方块上,颜色必须更改为任意方块。但我只能改变第一个方块的颜色。


为什么会发生这种情况?


我该如何解决这个问题?


let btn = document.querySelector("#btn");


btn.onclick = function createSquare() {

  let divSquare = document.createElement("div");

  divSquare.setAttribute("class", "square");

  divSquare.setAttribute("onmouseover", "mouseOver()");


  let container = document.querySelector("#container");

  container.appendChild(divSquare);

};


function mouseOver() {

  function getRandomColor() {

    let letters = "0123456789ABCDEF";

    let color = "#";

    for (let i = 0; i < 6; i++) {

    color += letters[Math.floor(Math.random() * 16)];

    }

  return color;

  }

let newColor = getRandomColor();

        

return document.querySelector('.square').style.backgroundColor = newColor;

}

#container {

  display: flex;

  width: 100%;

  height: 100%;

  flex-wrap: wrap;

}

.square {

  width: 100px;

  height: 100px;

  background-color: red;

  margin: 1px;

}

<button id="btn">Click here for create a new square</button>

<div id="container"></div>


我需要使用JS来解决这个问题


慕码人8056858
浏览 184回答 2
2回答

Qyouu

将事件参数 (e) 添加到 mouseOver func 并使用 e.target 获取框以设置背景function getRandomColor() {&nbsp; &nbsp; let letters = "0123456789ABCDEF";&nbsp; &nbsp; let color = "#";&nbsp; &nbsp; for (let i = 0; i < 6; i++) {&nbsp; &nbsp; &nbsp; &nbsp; color += letters[Math.floor(Math.random() * 16)];&nbsp; &nbsp; }&nbsp; &nbsp; return color;}function mouseOver(e) {&nbsp; let newColor = getRandomColor();&nbsp; return e.target.style.backgroundColor = newColor;}

qq_笑_17

我尝试按照 ControlAltDel 的方式进行解释,但没有成功,我将在其他时间研究这些事件。但是,我能够使用以下逻辑使代码工作:let btn = document.querySelector("#btn");btn.onclick = function createSquare() {&nbsp; let divSquare = document.createElement("div");&nbsp; divSquare.setAttribute("class", "square");&nbsp; divSquare.addEventListener("mouseover", function() {&nbsp; &nbsp; let letters = "0123456789ABCDEF";&nbsp; &nbsp; let color = "#";&nbsp; &nbsp; for (let i = 0; i < 6; i++) {&nbsp; &nbsp; &nbsp; color += letters[Math.floor(Math.random() * 16)];&nbsp; &nbsp; }&nbsp; &nbsp; return (this.style.backgroundColor = color);&nbsp; });&nbsp; let container = document.querySelector("#container");&nbsp; container.appendChild(divSquare);};#container {&nbsp; display: flex;&nbsp; width: 100%;&nbsp; height: 100%;&nbsp; flex-wrap: wrap;}.square {&nbsp; width: 100px;&nbsp; height: 100px;&nbsp; background-color: red;&nbsp; margin: 1px;}<button id="btn">Click here for create a new square</button><div id="container"></div>我避免使用 querySelector 并使用 addEventListener 来解决我的问题。谢谢你的帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript