javascript - 作为函数的结果增加特定元素的变量值

标签 javascript html css brightness

使用 for 循环,我创建了可变数量的 div,每当我用鼠标输入它们时,它们的背景颜色都会改变。好的是,每个 div 最终都有自己的颜色。现在我想添加一个函数,每当我用鼠标输入它时,它都会将 div 的亮度降低 10%。问题是,直到现在我只成功地减少了所有 div 的背景颜色,而不是个人的背景颜色。我很抱歉措辞如此糟糕,但会很感激任何帮助。

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>Etch-a-sketch</title>
  </head>
  <body>
    <h1>Etch-a-sketch</h1>
    <button id="start">Start</button>
    <div id="container"></div>
  </body>
  <script>


  //randomColor function is taken from http://www.devcurry.com/2010/08/generate-random-colors-using-javascript.html //
  function randomRgb() {

  col =  "rgb("
  + randomColor(255) + ","
  + randomColor(255) + ","
  + randomColor(255) + ")";
  }

  function randomColor(num) {
    return Math.floor(Math.random() * num);
  }

  function resetColorOfBoxes() {
    boxes = document.querySelectorAll('div');
    boxes.forEach(box => box.style.backgroundColor = "white");
  }

  function promptEntry() {

    let userInput = prompt("How many rows would you like?", "Enter a number");

    if (isNaN(userInput)) {
      alert("That's not a valid entry. Try again");
      promptEntry();
    }

    else {
      createGrid(userInput);
    }
  }

  function createGrid(numberOfRows) {

    resetColorOfBoxes()

    /*Change number of grid-template-columns and grid-template-rows under #container in stylesheet*/
    document.documentElement.style.setProperty("--columns-row", numberOfRows);

    let i = 0;
    let numberOfBoxes = numberOfRows**2;

    /*Create boxes*/
    for (i; i < numberOfBoxes ; i++) {
      var div = document.createElement("div");
      document.getElementById("container").appendChild(div);
      div.addEventListener("mouseenter", function () {
        randomRgb();
        this.style.backgroundColor = col;
        console.log(value);
      });
    }
  }

  let btn = document.getElementById("start")
  btn.addEventListener("click", promptEntry)

  </script>
</html>

这是提示(取自 theodinproject.com):

(可选):不是仅仅将网格的颜色从黑色更改为白色(例如),而是每次通过鼠标更改为完全随机的 RGB 值。然后尝试让每次通过只添加另外 10% 的黑色,这样只有在 10 次通过后方 block 才完全变黑。

谢谢!

最佳答案

我认为您走在正确的轨道上。

一种解决方法 注意:我已经删除了大部分包装代码,因此您可以了解概念并在之后根据需要设置样式。

function randomRgb() {
  return `rgb(${randomInt(255)},${randomInt(255)},${randomInt(255)})`;
}

function rgb2hex(rgb) {
  rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
  return (rgb && rgb.length === 4) ? '#' +
    ('0' + parseInt(rgb[1], 10).toString(16)).slice(-2) +
    ('0' + parseInt(rgb[2], 10).toString(16)).slice(-2) +
    ('0' + parseInt(rgb[3], 10).toString(16)).slice(-2) : '';
}

function randomInt(num) {
  return Math.floor(Math.random() * num);
}

/**
* @param color {string} HEX color
* @param amount {number}Can be negative for lighter color or positive for darker 
 * @return {string}
 */
function lightenDarkenColor(color, amount) {
  let usePound = false;
  if (color[0] === '#') {
    color = color.slice(1);
    usePound = true;
  }
  const num = parseInt(color, 16);
  let r = (num >> 16) + amount;
  if (r > 255) r = 255;
  else if (r < 0) r = 0;
  let b = ((num >> 8) & 0x00FF) + amount;

  if (b > 255) b = 255;
  else if (b < 0) b = 0;

  let g = (num & 0x0000FF) + amount;
  if (g > 255) g = 255;
  else if (g < 0) g = 0;

  return (usePound ? '#' : '') + (g | (b << 8) | (r << 16)).toString(16);

}

function createGrid(num) {
  const container = document.getElementById('container');
  for (let i = 0; i < num; i++) {
    const div = document.createElement('div');
    // Remove the next line, just for the demo
    div.innerHTML = `${i}`;
    const defaultColor = randomRgb();
    const hex = rgb2hex(defaultColor);
    const altColor = lightenDarkenColor(hex, -10);
    div.style.backgroundColor = defaultColor;
    // Remove the next line, just for the demo
    div.style.padding = '20px';
    div.onmouseout = function() {
      div.style.backgroundColor = defaultColor;
    };
    div.onmouseover = function() {
      div.style.backgroundColor = altColor;
    };
    container.appendChild(div);
  }
}
createGrid(10);
<h1>Please hover over the boxes </h1>
<div id="container"></div>

关于javascript - 作为函数的结果增加特定元素的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50839642/

相关文章:

javascript - 单击按钮时重写 javascript 变量值

javascript - 如何将文本框中的值保存到变量

CSS - 变换 : scale() irrespective of element size

html - 如何创建关闭所有弹出窗口的操作?

html - 模态弹出窗口溢出

javascript - javascript try catch语句在我的代码中不起作用

javascript - 在 XHTML 文档中引用 javascript 的最佳位置在哪里

javascript - getParent函数在ie中不起作用

javascript - 在 javascript 中打印 html 的最佳实践

css - bootstrap3 将 div 彼此相邻对齐