涉及知识点
介绍
整体是有很多方格组成的矩阵,鼠标滑入每个方格会随机显示不同的颜色,鼠标滑出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);
}
}