鼠标进入,鼠标离开 epmty DIV。更改颜色并将其删除
Mouseenter, mouseleave in epmty DIV. Change a color and remove it
我在 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>
我在 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>