鼠标输入,鼠标离开 epmty DIV. 更改颜色并将其删除



我有一个简单的 html 代码,带有 css 和 js...但它没有运行。 我是JS的初学者,我找不到为什么我的鼠标悬停(我什至尝试过mouseenter(不起作用。有人可以向我解释一下吗? 此外,我需要做鼠标离开,所以当用户离开框时,红色消失了。 我知道伙计们这很简单,但我无法解决它:(

谢谢

div {
width: 300px;
height: 300px;
border: 1px solid black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div></div>
<script>
var box = document.querySelector('div')[0];
if (box) {
box.addEventListener('mouseover', colorin);
}
function colorin(e) {
e.style.backgroundColor = "red";
}
</script>
</body>
</html>

我附上了下面的工作代码,您需要将e.style.backgroundColor = "red";更改为e.target.style.backgroundColor = "red";如果没有 .target,就没有要更改的 DOM 元素。此外,正如您提到的,您需要有一个 mouseout 事件,当用户不再关注该div 时,该事件会将颜色恢复为白色。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div {
width: 300px;
height: 300px;
border: 1px solid black;
}
</style>
</head>
<body>
<div></div>
<script>
var box = document.querySelector('div');
if(box) {
box.addEventListener('mouseenter', colorin);
box.addEventListener('mouseout', colorout);
}
function colorin(e) {
e.target.style.backgroundColor = "red";
}
function colorout(e) {
e.target.style.backgroundColor = "white";
}
</script>
</body>
</html>

最新更新