首页 > 解决方案 > 仅当激活随机按钮时颜色才会改变

问题描述

我正在做一个 Etch-a-sketch 项目,我的问题是,颜色只有在我单击随机按钮时才会改变,我希望它在我将鼠标悬停在网格上的不同单元格时改变。

这是一个 repl:https ://repl.it/@antgotfan/etch-a-sketch - 这显示了所有内容(html、css、js 和 jquery)

链接到我希望我的 etch-a-sketch 做什么:https ://codepen.io/beumsk/pen/dVWPOW?editors=0110

我尝试使用 event.target ,但我真的无法理解事件正在做什么。

$randomButton.on("click", getRandomColors);
$resetButton.on("click", reset);

/*--------------------------- Corresponding to Event listeners ---------------------------*/
function getGradient(event) {

}

function getRandomColors() {
    let colorR = Math.floor((Math.random() * 256));
    let colorG = Math.floor((Math.random() * 256));
    let colorB = Math.floor((Math.random() * 256));
    $(".cell").hover((event) => $(event.target).css({
                                                    "backgroundColor": `rgb(${colorR}, ${colorG}, ${colorB})`,
                                                    "opacity": "1"}));
}

标签: javascriptjqueryhtmlcss

解决方案


您必须在绑定事件处理程序之前在事件处理程序中生成颜色(即触发事件时)。

function getRandomColors() {
  $(".cell").hover(function (event) {
    let colorR = Math.floor((Math.random() * 256));
    let colorG = Math.floor((Math.random() * 256));
    let colorB = Math.floor((Math.random() * 256));
    $(event.target).css({ "backgroundColor": `rgb(${colorR}, ${colorG}, ${colorB})`, "opacity": "1" })
  });
}

推荐阅读