首先是HTML标签,创作一个容器
<body>
<div id="container"></div>
</body>
其次是style样式标签:
<style>
* {
box-sizing: border-box;
}
body {
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background-color: #333;
}
#container {
width: 450px;
height: 300px;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-content: space-between;
}
.item {
width: 20px;
height: 20px;
margin: 5px;
background-color: #666;
}
</style>
<script>
var container = document.querySelector("#container");
function getRandomColor() {
var color = "#";
var chars = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"A",
"B",
"C",
"D",
"E",
"F",
];
for (var i = 0; i < 6; i++) {
var index = Math.floor(Math.random() * chars.length);
color += chars[index];
}
return color;
}
for (var i = 0; i < 150; i++) {
var span = document.createElement("span");
span.classList.add("item");
// 事件注册
span.onmouseenter = function (e) {
var target = e.target;
target.style.backgroundColor = getRandomColor();
};
span.onmouseout = function (e) {
setTimeout(function () {
e.target.style.backgroundColor = "#666666";
}, 500);
};
container.appendChild(span);
}