详细代码和解释
//获取元素
const box = document.getElementById("box");
//创建能获得随机颜色的类
const Color = {
colorChar: "1234567890abcdef",
getColor() {
let color = "";
for (let i = 0; i < 6; i++) {
color += this.colorChar[getRandomArbitrary(0, this.colorChar.length)];
}
return `#${color}`;
}
}
//这是一个获得随机数的函数
function getRandomArbitrary(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
//改变颜色,用于点击事件的callback
function changeColor(event) {
//好像在target里面可以修改style属性,但是我没看到
//如果没有使用类的话就只是编译一次,多次点击不会变化颜色,使用类可以多次点击
event.target.style.backgroundColor = Color.getColor();
event.target.textContent = "鼠标触发点击事件,改变背景颜色,请移出或者重新进入";
}
//定义一个盒子发生颜色改变的函数
function changeBoxColor(element) {
element.style.backgroundColor = Color.getColor();
element.style.color = Color.getColor();
element.style.border = `20px solid ${Color.getColor()}`;
}
//点击事件
box.addEventListener("click", changeColor);//click点击事件,函数
//鼠标覆盖
box.addEventListener("mouseover", (event) => {
event.target.style.border = `20px solid ${Color.getColor()}`;
event.target.textContent = "鼠标移入触发mouseover事件,改变边框颜色,请点击或者移出";
});
//鼠标移出
box.addEventListener("mouseout",(event) => {
event.target.style.color = Color.getColor();
event.target.textContent = "鼠标移出触发mouseout事件,改变文字颜色,请点击或者移入";
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="box">
请将鼠标移入👍
</div>
<!-- <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quo beatae nisi aliquam maxime eos laudantium voluptatibus deserunt ea perspiciatis odio hic nemo consequatur praesentium, assumenda dignissimos! Dicta itaque quos eos!</p> -->
<script src="index.js"></script>
</body>
</html>
body{
box-sizing: border-box;
font-family: Verdana, Geneva, Tahoma, sans-serif;
font-size: 2em;
}
#box{
border: 3px solid;
width: 300px;
height: 300px;
font-size: 1em;
background-color: lightblue;
display: flex;
text-align: center;
justify-items: center;
align-items: center;
}
#box:hover{
box-shadow: 3px 3px 5px black;
}