香草 JS 将鼠标悬停在 div 上更改背景颜色

vanilla JS hover over div change background color

我正在构建一个类似于 Etch-a-Sketch 的交互式网格。我设置了我的网格,现在我正在尝试设置一个“悬停”效果,以便当您的鼠标经过它们时网格 div 会改变颜色,像钢笔一样在您的网格中留下(像素化)轨迹。但我希望颜色根据单击的按钮而改变;即,当您悬停时,黑色按钮会留下黑色轨迹,而彩虹会留下彩虹轨迹,然后重置会清除网格。

<head> 
  <title> Claudias Etch-A-Sketch</title>
  <link rel= "stylesheet"  href="style.css">

</head>
<body>
  <section class="black"> 
    <h1><center> Claudia Etch-A-Sketch!</center></h1>
  </section>

  <section>
    <div class="buttons">
      <button id="rainbow">Rainbow</button>
      <button id="black">Black</button>
      <button id="reset">Reset</button>
    </div>
  </section>
  <section>
    <div id="container"> </div>
  </section>
</body>


<script src="javascript.js"></script>
const container = document.getElementById("container");
const btnReset = document.getElementById("reset");
const btnBlack = document.getElementById("black");
const btnRainbow = document.getElementById("rainbow");

function makeRows(rows, cols) {
  container.style.setProperty('--grid-rows', rows);
  container.style.setProperty('--grid-cols', cols);
  for (c = 0; c < (rows * cols); c++) {
    let cell = document.createElement("div");

    container.appendChild(cell).className = "grid-item";
  };
};

makeRows(16, 16);
:root {
  --grid-cols: 1;
  --grid-rows: 1;
}

#container {
  display: grid;
  grid-template-rows: repeat(var(--grid-rows), 1fr);
  grid-template-columns: repeat(var(--grid-cols), 1fr);
}

.grid-item {
  height: 30px;
  width: 30px;
  border: 1px solid #ddd;
  text-align: center;
}  

.black {
  background-color: black;
}

h1 {
  color: white;
}

既然你想要一条轨迹,你需要永久改变颜色,而不仅仅是悬停,所以你需要使用javascript。

在创建网格时为每个网格项添加一个事件侦听器:

cell.addEventListener('mouseover', 
  e => e.target.classList.add('my-colour-class')
)

然后确保您的 my-colour-class 具有合适的样式

.my-color-class {
  background-colour: blue;
}

注意,要更改应用的 class(根据选择的笔更改轨迹颜色)将当前颜色存储在状态变量中并制作地图,例如

let currentColor = 'black'

const colors = { black: 'black' }

e => e.target.classList.add(colors[currentColor])
.grid-item {
    height: 30px;
    width: 30px;
    border: 1px solid #ddd;
    text-align: center;
    transition: ease 3s all;
}

.grid-item:hover {
    background-color: blue;
    transition: ease 0.1s all;
}

我们可以使用 css 技巧添加 :hover 动画