悬停(Hover)是指鼠标指针停留在某个元素上。在网页设计中,悬停效果常用于提示信息、导航菜单等交互元素。通过CSS和JavaScript,可以实现当鼠标悬停在某个元素上时,显示或隐藏子菜单。
:hover
伪类实现悬停效果。mouseenter
和mouseleave
)来实现悬停效果。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hover Menu Example</title>
<style>
.menu-item {
position: relative;
display: inline-block;
margin-right: 20px;
}
.sub-menu {
display: none;
position: absolute;
top: 100%;
left: 0;
background-color: #f9f9f9;
padding: 10px;
border: 1px solid #ccc;
}
.menu-item:hover .sub-menu {
display: block;
}
</style>
</head>
<body>
<div class="menu-item">
Menu Item 1
<div class="sub-menu">
Sub Menu Item 1.1
<br>
Sub Menu Item 1.2
</div>
</div>
<div class="menu-item">
Menu Item 2
<div class="sub-menu">
Sub Menu Item 2.1
<br>
Sub Menu Item 2.2
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hover Menu Example</title>
<style>
.menu-item {
position: relative;
display: inline-block;
margin-right: 20px;
}
.sub-menu {
display: none;
position: absolute;
top: 100%;
left: 0;
background-color: #f9f9f9;
padding: 10px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div class="menu-item" onmouseover="showSubMenu(this)" onmouseout="hideSubMenu(this)">
Menu Item 1
<div class="sub-menu">
Sub Menu Item 1.1
<br>
Sub Menu Item 1.2
</div>
</div>
<div class="menu-item" onmouseover="showSubMenu(this)" onmouseout="hideSubMenu(this)">
Menu Item 2
<div class="sub-menu">
Sub Menu Item 2.1
<br>
Sub Menu Item 2.2
</div>
</div>
<script>
function showSubMenu(element) {
element.querySelector('.sub-menu').style.display = 'block';
}
function hideSubMenu(element) {
element.querySelector('.sub-menu').style.display = 'none';
}
</script>
</body>
</html>
position
属性设置为absolute
,并且父元素的position
属性设置为relative
。transition
属性来平滑显示和隐藏效果。通过以上方法,你可以实现一个在悬停时打开菜单的功能,提升用户体验和交互效果。
领取专属 10元无门槛券
手把手带您无忧上云