我正在做一个“像素艺术”网页,当我没有按下鼠标上的按钮时,我不希望“铅笔”进行绘制,我尝试这样做,但是我可以让“铅笔”工作通过单击或鼠标悬停。总之,我想单击并继续拖动鼠标以按下单击进行绘制。
我的代码现在所做的是使用鼠标悬停而不按下。希望你能帮助我
const GRIDSIDE = 600;
let side = 16;
const grid = document.querySelector(".grid");
for (let i = 0; i < (side * side); i++) {
const gridElement = document.createElement("div");
grid.appendChild(gridElement);
gridElement.classList.add("gridElement");
gridElement.style.width = `${(GRIDSIDE / side) - 2}px`;
gridElement.style.height = `${(GRIDSIDE / side) - 2}px`;
gridElement.addEventListener("mousedown", addColor);
gridElement.addEventListener("mouseover", addColor);
}
function addColor() {
this.style.backgroundColor = "black";
}
body {
background-color: aliceblue;
}
.grid {
width: 600px;
height: 600px;
margin: 100px auto;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
background-color: white;
box-shadow: 10px 10px #D6EAF8;
}
.gridElement {
flex: none;
border: 1px solid whitesmoke;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Etch-A-Sketch</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="grid"></div>
<script src="script.js"></script>
</body>
</html>
首先,您的模板文字周围没有反引号,并且
px
需要连接到模板文字,而不仅仅是文字旁边的字符。
现在,可能有一种更简洁的方法来做到这一点,但在我看来,你需要 3 个事件:一个启动突出显示,一个在移动鼠标时继续突出显示,一个取消突出显示。
查看内嵌评论:
const GRIDSIDE = 600;
let side = 16;
const grid = document.querySelector(".grid");
let active = false;
for (let i = 0; i < (side * side); i++) {
const gridElement = document.createElement("div");
grid.appendChild(gridElement);
gridElement.classList.add("gridElement");
gridElement.style.width = `${(GRIDSIDE / side) - 2}` + "px";
gridElement.style.height = `${(GRIDSIDE / side) - 2}` + "px";
// Start a new highlighting session when a click happens
gridElement.addEventListener("mousedown", function(){begin(this)});
// Continue highlighting while mouse moves
gridElement.addEventListener("mousemove", function(){addColor(this)});
// Stop highlighting session
gridElement.addEventListener("mouseup", function(){stop(this)});
}
function begin(gridEl) {
active = true;
gridEl.style.backgroundColor = "black";
}
function addColor(gridEl) {
if (active) {
gridEl.style.backgroundColor = "black";
}
}
function stop(gridEl) {
active = false;
}
body {
background-color: aliceblue;
}
.grid {
width: 600px;
height: 600px;
margin: 100px auto;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
background-color: white;
box-shadow: 10px 10px #D6EAF8;
}
.gridElement {
flex: none;
border: 1px solid whitesmoke;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Etch-A-Sketch</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="grid"></div>
<script src="script.js"></script>
</body>
</html>