【发布时间】:2020-01-13 16:48:25
【问题描述】:
我正在尝试做一个 Etch-A-Sketch 项目,但目前遇到了一些障碍。目前能够根据提示根据用户输入创建网格并通过按钮清除网格。
我现在面临的问题是function colorChange(),我试图在每次在 div 上捕获鼠标悬停事件时增加背景颜色的不透明度。一切正常,但在当前代码中不透明度最高为 0.9。
如果改为使用if (rgbaValue <= 0.9) 或(rgbaValue < 1),则不透明度值会在 0.9 之后的下一次悬停时重置为 0.1。如何在不重置的情况下将不透明度设为 1?
代码如下:
html
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="style.css">
<title>Etch A Sketch</title>
<body>
<div>
<button type="button" onclick="clearGrid()">Click to clear grid</button>
</div>
<div id="container"></div>
<script src="java.js"></script>
</body>
</html>
javascript
let gridSize = 0;
let gridWidth = 0;
gridSize = window.prompt("Please input the amount of squares per side of grid that you want created");
gridWidth = 100/gridSize;
createGrid();
colorChange();
function createSquare() {
const mainBody = document.querySelector("#container");
const gridMake = document.createElement("div");
gridMake.classList.add("squaregrid");
gridMake.style.width = gridWidth + "%";
gridMake.style.paddingBottom = gridWidth + "%";
mainBody.appendChild(gridMake);
}
function createGrid() {
gridCount = 0;
while (gridCount < (gridSize*gridSize)) {
createSquare();
gridCount++
}
}
function colorChange() {
const selectSquare = document.querySelectorAll(".squaregrid");
selectSquare.forEach(square => square.addEventListener("mouseover", event => {
square.classList.add('hover-change');
const style = getComputedStyle(square);
let styleDeep = style.backgroundColor;
rgbaValue = parseFloat(styleDeep.replace(/^.*,(.+)\)/,'$1'));
if (rgbaValue < 0.9) {
square.style.backgroundColor = `rgba(0,0,0, ${rgbaValue + 0.1})`;
}
}))
}
function clearGrid() {
const squareReset = document.querySelectorAll(".squaregrid");
squareReset.forEach(square => square.style.backgroundColor = "");
squareReset.forEach(square => square.classList.remove("hover-change"));
}
css
.squaregrid {
box-sizing: border-box;
display: inline-block;
border: 0.05px solid black;
margin:0;
}
html, body {
line-height: 0;
height: 94vh;
width: 94vh;
margin-left: auto;
margin-right: auto;
}
#container {
display: block;
overflow: hidden;
margin-left: auto;
margin-right: auto;
border: 0.05px solid black;
}
.hover-change {
background-color: rgba(0, 0, 0, 1);
}
button {
display: block;
margin-bottom: 5px;
}
【问题讨论】:
-
你的问题是什么?
-
哎呀。我将如何将不透明度值设为 1?我会将其编辑为主要问题
-
如果您将
background-color设置为rgba(0, 0, 0, 1);而只是修改了opacity会怎样?这会稍微简化 javascript。 -
@LucaNeri 谢谢!那是我增加网格不透明度的第一个版本。然而,这会影响包括边框在内的整个 div,而 rgba 中的 alpha 只影响背景颜色,在这种情况下这是一个更可取的结果?或者,我可以将方形 div 放置在另一个方形 div 中,因为边框和不透明度只会影响内部 div,但这似乎是一个更长的解决方案?
-
请您显示其余的css和html,以便我看到任何问题。此外,在 Stack Overflow 上,最好显示与您的问题相关的所有代码。
标签: javascript html css