-4

我被要求构建一个 HTML 和 CSS 页面,其中包含 4 个不同颜色的正方形,它们的大小是彼此的两倍(例如,第一个 2x2 像素,第二个 4x4,第三个 8x8 和第四个 16x16),当光标悬停在方块上,对应的方块接收到它旁边方块的颜色。

4

2 回答 2

0

这是给你的简短片段。它显示了主要概念,然后您可以以某种方式对其进行调整以准确地实现您所需要的。

const INIT_SIZE = [20,20];
const COLORS = ['red','green','blue','yellow'];

const squares = COLORS.map((color, index) => {
  const el = document.createElement('div');
  el.style.width = INIT_SIZE[0] * Math.pow(2, index) + 'px';
  el.style.height = INIT_SIZE[1] * Math.pow(2, index) + 'px';
  el.style.backgroundColor = color;
  document.body.appendChild(el);
  return el;
});

squares.forEach((sq) => {
  sq.addEventListener('mouseover', (ev) => {
    const tgt = ev.target;
    const curr = squares.indexOf(tgt);
    const newIndex = (curr + 1) == squares.length ? 0 : (curr + 1);
    tgt.style.backgroundColor = squares[newIndex].style.backgroundColor;
  })
})

于 2019-05-30T15:02:34.920 回答
-1
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
<style>
 .box1{
  width:20px;
  height:20px;
  background-color:blue
}
 .box2{
  width:40px;
  height:40px;
  background-color:black
 }
.box3{
  width:80px;
  height:80px;
  background-color:yellow
}
.box4{
 width:160px;
 height:160px;
 background-color:green
} 
<script>
 document.querySelector(".box1").addEventListener("mouseenter",function(){
 document.querySelector(".box3").style.backgroundColor="red";
})
<style>

这是第一个盒子的演示链接。您必须设置应该手动更改的框 https://jsfiddle.net/xj60tq4d/1/

于 2019-05-30T14:56:04.930 回答