当我把鼠标悬停在div上时,有没有办法停止出现故障



我正在编写这个程序,它要求我更改mouseover((上文本的格式和位置,并返回到mouseout((上的默认属性。然而,当我将鼠标悬停在文本上时,它开始出现故障。有什么办法阻止这种情况吗?

这是我的完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Week6</title>
<style>
#p1{
font-size: 2em;
color: blue;
}
#div1{
position: absolute;
visibility: visible;
padding: 0px;
}
h1{
font-size: 3em;
color: yellow;
font-style: italic;
}
#div2{
display: flex;
justify-content: center;
margin-top: -10px;
left: 500px;
visibility: hidden;
}
</style>

</head>
<body>
<div id="div1">
<h2>Move the cursor over the text to see it change.</h2>
</div>
<div id="div2">
<h1>Move the cursor over the text to see it change.</h1>
</div>



</body>
</html>
<script>
let div1 = document.getElementById("div1");
let div2 = document.getElementById("div2");
div1.addEventListener('mouseover', (e) => {
div1.style.visibility = "hidden";
div2.style.visibility = "visible";
e.preventDefault();
});

div1.addEventListener('mouseout', ()=>{
div1.style.visibility = "visible";
div2.style.visibility = "hidden";
})
</script>

为什么要使用JavaScript使元素可见?使用CSS时很简单。我希望这个代码能对你有很大帮助。尝试使用CSS而不是JavaScript。

<!DOCTYPE html>
<html>
<head>
<style>
.div2 {
visibility:hidden;
}

.div1:hover + .div2 {
visibility:visible;
color: red;
}
</style>
</head>
<body>
<h2>Display an Element on Hover</h2>
<div class="div1">Hover over me.</div>
<div class="div2">I am shown when someone hovers over the div above.</div>
</body>
</html>

相关内容

最新更新