前端小项目 HoverBoard 方格矩阵hover随机颜色动画

涉及知识点

介绍

整体是有很多方格组成的矩阵,鼠标滑入每个方格会随机显示不同的颜色,鼠标滑出2s后颜色消失。
请添加图片描述
给方格设置 transtion-duration ,那滑入滑出的时间都是一致的,可以再给方格的hover态设置 transition-duration 为0,那么移入方格时的动画时间就是0 ,不影响移出时间了。

代码

无html,css:

body{
    font-size: 0;
    background-color: black;
}
ul{
    display: inline-block;
    margin: 0px;
    padding: 0px;
    font-size: 0;
}
.box{
    width: 20px;
    height: 20px;
    background-color:#1d1d1d;
    transition: 2s ease;
    list-style: none;
    margin: 4px 2px;
}
.box:hover{
    transition: 0s;
}

js:

init(20);
var ulEls = document.querySelectorAll('ul');
ulEls.forEach(function (ulEl) {
    ulEl.addEventListener('mouseover', function (e) {
        if (e.target.nodeName === 'LI') {
            setColor(e.target, colorRandom());
        }
    });
    ulEl.addEventListener('mouseout', function (e) {
        if (e.target.nodeName === 'LI') {
            removeColor(e.target);
        }
    });
});
function setColor(el, rgb) {
    el.style.backgroundColor = rgb;
    el.style.boxShadow = "1px 1px 4px " + rgb;
}
function removeColor(el) {
    el.style.backgroundColor = '#1d1d1d';
    el.style.boxShadow = "1px 1px 4px #1d1d1d";
}
function colorRandom() {
    var r = Math.floor(Math.random() * 255);
    var g = Math.floor(Math.random() * 255);
    var b = Math.floor(Math.random() * 255);
    return "rgb(" + r + "," + g + "," + b + ")";
}
function init(len) {
    for (var i = 1; i < len; i++) {
        var ul = document.createElement('ul');
        for (var i_1 = 1; i_1 < len; i_1++) {
            var li = document.createElement('li');
            li.classList.add('box');
            ul.appendChild(li);
        }
        document.body.appendChild(ul);
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值