javascript - 仅当激活随机按钮时颜色才会改变
问题描述
我正在做一个 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"}));
}
解决方案
您必须在绑定事件处理程序之前在事件处理程序中生成颜色(即触发事件时)。
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" })
});
}
推荐阅读
- xcode - 如何为多种 iPhone 尺寸对齐文本和图像
- azure-data-explorer - Kusto 流式摄取:ErrorReason=Not Found
- c# - 如何使用 EntityFramework 设置 FORCEPLAN?
- android-studio - 当我发布带有滥用功能的应用程序时,无法正常工作错误充气类按钮。只有经常使用
- c++ - 如何将不同的 C++ 类映射到枚举类值
- c++ - 如何将txt文件读入存储在类变量中的数组中?
- swift - 设置 UIBarButtonItem 外观会导致后退按钮出现奇怪的行为
- python - 我无法在 python 中正确地将我想要的值分配给变量
- python - UDP Tracker 只给我我的 ip 作为宣布请求的答案
- python - 图像分类模型中非常高的过拟合