[英]Using Mouseenter / MouseLeave to Change Div in JavaScript
[英]Mouseenter, mouseleave in epmty DIV. Change a color and remove it
我在css和js的html中有这个简单的代码...但是它没有运行。 我是JS的初学者,我无法找出为什么我的mouseover(甚至尝试过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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.