HTML
首先,我们创建一个简单的HTML结构,包含一个父元素和一个子元素。子元素默认是隐藏的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mouse Enter Show/Hide Example</title>
<link rel="stylesheet" href="style.css"> <!-- 引入CSS -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- 引入jQuery -->
<script src="script.js"></script> <!-- 引入JavaScript -->
</head>
<body>
<div class="parent">
Hover me!
<div class="child" style="display: none;">
I appear on hover!
</div>
</div>
</body>
</html>
CSS (style.css)
接下来,我们用CSS来设置一些基本样式,并定义子元素隐藏时的状态。
.parent {
width: 200px;
height: 100px;
background-color: lightblue;
text-align: center;
line-height: 100px;
cursor: pointer;
}
.child {
width: 100%;
height: 50px;
background-color: lightgreen;
text-align: center;
line-height: 50px;
margin-top: 5px;
}
JavaScript (script.js)
最后,我们使用jQuery来处理鼠标进入父元素和离开子元素的事件。
$(document).ready(function() {
$('.parent').mouseenter(function() {
$('.child', this).show(); // 当鼠标进入父元素时,显示子元素
});
$('.child').mouseleave(function() {
$(this).hide(); // 当鼠标离开子元素时,隐藏子元素
});
});
这段代码中,.mouseenter()
和 .mouseleave()
是jQuery的方法,分别用于监听鼠标进入和离开元素的事件。当鼠标进入.parent
元素时,会执行.child
元素的.show()
方法使其显示;当鼠标离开.child
元素时,则执行.hide()
方法使其隐藏。
这样就实现了鼠标进入父元素时显示子元素,离开子元素时子元素消失的效果