我目前正在做Odin项目的蚀刻草图项目,遇到了一个问题,当我在绘图网格上单击并拖动鼠标时,光标有时会变成块图标.我现在有一个变量isPainting
,它充当网格上绘图的布尔值,在mousedown上为true,在mouseup上为false
下面的按钮目前不起作用,因为我更专注于让绘图工作.附件是我的html、css和javascript代码.
let isPainting = false;
document.body.onmousedown = () => (isPainting = true);
document.body.onmouseup = () => (isPainting = false );
function populatePage(size){
let board = document.querySelector(".board");
let squares = board.querySelectorAll("div");
squares.forEach((div) => div.remove());
board.style.gridTemplateColumns = `repeat(${size}, 1fr)`;
board.style.gridTemplateRows = `repeat(${size}, 1fr)`;
let amount= size * size;
for(var i = 0; i < amount; i++){
let square = document.createElement('div')
square.addEventListener('mouseover',colorSquare);
square.addEventListener('mousedown',colorSquare);
square.style.backgroundColor = 'grey';
board.insertAdjacentElement('beforeend',square);
}
}
function colorSquare(e){
if(isPainting){
this.style.backgroundColor = 'black';
}
}
populatePage(16);
.board{
width: 500px;
height: 500px;
display: grid;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel = "stylesheet" href="styles.css">
<link rel = "stylesheet" href="normalize.css">
<title>Etch-a-Sketch</title>
</head>
<body>
<div class="flex-container">
<div class="header">
<h1>Etch a Sketch</h1>
<h2></h2>
</div>
<div class="content">
<div class="board"></div>
<div class="buttons">
<button>Black</button>
<button>Erase</button>
<button>Random</button>
<button>Reset</button>
</div>
</div>
<button>Set Size</button>
</div>
</body>
<script src="main.js"></script>
</html>
预期结果:只有按住鼠标按钮并在网格上移动时,用户才能在蚀刻草图网格上绘制.释放鼠标按钮时,绘图将停止.
实际结果:有时当鼠标按下并移动时,光标会变成一个"块"图标,绘图将停止或仍然绘图,尽管鼠标按钮已经向上.