原生js练手小项目-鼠标跟随调色板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="mystyle.css">
    <title>Color Board2</title>
</head>
<body>
    <div id="container">
    </div>
    <script src="myscript.js"></script>
</body>
</html>
*{
    box-sizing: border-box;
}
/* 用flex方便居中 */
body{
    margin: 0;
    background: #111;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
}
/* 设置容器最大宽度400px,内部所有item居中显示 */
#container{
    display: flex;
    align-items: center;
    justify-content: center;
    max-width: 400px;
    flex-wrap: wrap;
}
/* 设置小方块的背景,大小,设置动画时长和ease效果 */
.square{
    background: rgb(39, 37, 37);
    width: 16px;
    height: 16px;
    margin: 2px;
    box-shadow: 0 0 2px black;
    transition: 2s ease;
}
/* 设置小方块悬停伪类的变换时间是立马变换 */
.square:hover{
    transition-duration: 0s;
}

// 获取节点
const container = document.getElementById("container");

//颜色列表
const colors = ['#363062','#ef962d','#fde2e2','#00bdaa','#00a8cc','#d8ebb5','#fbcffc','#f8615a','#a6b1e1','#f6eec7'];
//小方块个数
const squareNum = 400;

//生成小方块方法
function squareGenerator(){
    for(let i=0;i<squareNum;i++){
        const square = document.createElement('div');
        square.classList.add('square');
        //对每一个square绑定监听事件
        //mouseover事件
        square.addEventListener('mouseover',() => {
            const color = getRandomColor();
            square.style.background = color;
            square.style.boxShadow = `0 0 2px ${color} 0 0 10px ${color}`;
        })
        //mouseout事件
        square.addEventListener('mouseout',() => {
            square.style.background = 'rgb(39, 37, 37)';
            square.style.boxShadow = `0 0 2px black`;
        })

        container.append(square);
    }
}
//获取随机颜色的方法
function getRandomColor(){
    return colors[Math.floor(Math.random()*colors.length)];
}

squareGenerator()

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值