【问题标题】:RGBA opacity reseting (Etch-A-Sketch)RGBA 不透明度重置 (Etch-A-Sketch)
【发布时间】: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


【解决方案1】:

您的代码的主要问题与浏览器的方式有关 处理完全不透明度。

rgba() 表示法接受 0.0 到 1.0(含)范围内的数字或百分比,其中数字 1 对应于 100%,for the value of the alpha channel。任何超出区间的值,虽然有效,但都被限制在范围内最近的限制。

大于 1 或 100% 的值将被限制,并且 从计算值中省略

background-color: rgba(0, 0, 0, 0.5);  # computed (0, 0, 0, 0.5)
background-color: rgba(0, 0, 0, 1);    # computed (0, 0, 0)
background-color: rgba(0, 0, 0, 1.3);  # computed (0, 0, 0)

您的正则表达式正在捕获最后一个逗号之间的任何字符 在 rgba() 表示法和计算的右括号中 价值。当您分配后触发事件侦听器时 正方形 alpha 值等于或大于 1 您的正则表达式捕获 0 并相应地设置 alpha 值。

在下面的代码 sn-p 中,您可以看到使用其他正则表达式解决问题的一种方法。

或者,您可以将 opacity 属性用作@Luca Neri 已经推荐了。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
  <meta name="author" content="">
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body, html {
        margin: 0;
    }
    .squaregrid {
        display: grid;
    }
    .square {
        background-color: rgba(20, 20, 20, 0.1);
    }
    button {
        position: fixed;
        bottom: 0;
    }
  </style>
</head>
<body>
  <div class="squaregrid"></div>
  <button onclick="clearScreen()">CLEAR</button>
  <script>
   //request number of rows
   let rows = window.prompt("ENTER NUMBER OF ROWS")
   //create a grid
    document.getElementsByClassName("squaregrid")[0].style.gridTemplateColumns =   "repeat("+ 1000/rows+", 1fr)"
    //create Squares
    for (let i = 0; i < 1000; i++)   {
        let newSquare = document.createElement("div")
        newSquare.className = "square"
        newSquare.style.height = 100/rows + "vh"
        document.querySelector(".squaregrid").appendChild(newSquare)
    }  
    //get HTML Collection of all squares
    let allSquares = document.getElementsByClassName("square");
    //loop HTML Collection and add a mouseover event listener to each square
    for (square of allSquares) {
      square.addEventListener("mouseover", event => {
        //get computed background-color value of the square being hovered over
        let squareBackground = getComputedStyle(event.target).backgroundColor;
        //the regular expression
        let regex = /\d\.\d/
        //check if does not already have full opacity
        if (squareBackground.match(regex) != null) {
            //get the alpha channel of the square being hovered over
            let squareOpacity  = Number(squareBackground.match(regex))
            //increase alpha value
            event.target.style.backgroundColor = squareBackground.replace(regex, squareOpacity + 0.1)
        }
    })}
    //reset every square on the grid
    function clearScreen() {
      for (square of allSquares) {
        square.style.backgroundColor = "rgba(20, 20, 20, 0.1)"
      }
    }
    </script>
  </body>
</html>

感谢@disinfor 的反馈。

【讨论】:

  • 欢迎来到 Stack Overflow!虽然这可能是答案,但请发布为什么它回答了这个问题。由于这是一段代码,因此最好解释一下您更改了什么以及如何解决它。
  • 感谢Vito的详细解释,我去试试这个再回来。
  • 感谢 Vito,我更改了使用的正则表达式并合并了空检查。一切都按预期工作。再次感谢您的详细解释和代码。在这个学习过程中真的帮助了我。
猜你喜欢
  • 2020-05-13
  • 1970-01-01
  • 2013-06-26
  • 1970-01-01
  • 2011-05-10
  • 2014-10-21
  • 1970-01-01
  • 2012-11-03
  • 2014-04-19
相关资源
最近更新 更多