我正在使用Vanilla Javascript进行Odin Project Etch-A-Sketch项目:更多细节。
实时预览:https://purplepineapple123.github.io/etch-a-sketch/
首先,我在javascript中动态创建了div网格,并成功创建了按钮(黑色,迷幻和用户颜色选择)来改变每个子div网格元素的颜色。
我遇到的问题是一个优化问题。每次用户单击按钮时,都会触发该事件,并且在后续单击按钮时不会忘记该事件。例如,如果您单击"迷幻"按钮。5次,然后悬停在网格上,console.log显示你悬停在每个网格上的颜色5次。
请注意,在这个截图中,只有一个网格被突出显示,但是console.log的颜色是每个按钮按下的分层div(我在这个例子中使用了psychedelic-button
)。
这个分层问题在"chooseColor""按钮。如果用户使用颜色选择器选择了多种不同的颜色,那么console.log将显示每个mouseEnter事件的指数重复输出。这会导致大量的延迟。
我尝试过的事情:
- 添加和删除类,而不是更改背景颜色。这工作得很好,除了我不知道如何将迷幻(随机JS选择的颜色)添加到css类。
- 移除createGrid()主函数之外的变色函数。这没有影响任何东西,因为我认为问题是由多次点击按钮引起的。
- 将颜色变化函数移到createGrid()函数之外。然后抓住divCol类。将该nodeList转换为Array。添加mouseEnter eventListener forEach元素,然后更改颜色。同样的问题,重复的每个按钮点击。
我如何防止这个div堆叠和延迟从累积的按钮点击?
我代码: