CSS(层叠样式表)和JS(JavaScript)是构建网页交互性的两个关键技术。CSS负责页面的样式和布局,而JS则负责页面的动态行为和交互逻辑。
菜单栏展开收缩是一种常见的网页交互效果,通常用于导航菜单。用户点击菜单栏时,菜单项会展开显示子菜单项,再次点击则收缩隐藏子菜单项。
:hover
伪类或CSS动画来实现菜单的展开和收缩。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Menu Toggle</title>
<style>
.menu {
display: flex;
list-style: none;
padding: 0;
}
.menu-item {
position: relative;
}
.sub-menu {
display: none;
position: absolute;
top: 100%;
left: 0;
background-color: #fff;
border: 1px solid #ccc;
}
.menu-item:hover .sub-menu {
display: block;
}
</style>
</head>
<body>
<ul class="menu">
<li class="menu-item">
Home
</li>
<li class="menu-item">
Products
<ul class="sub-menu">
<li>Product 1</li>
<li>Product 2</li>
<li>Product 3</li>
</ul>
</li>
<li class="menu-item">
About
</li>
</ul>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS Menu Toggle</title>
<style>
.menu {
display: flex;
list-style: none;
padding: 0;
}
.menu-item {
position: relative;
}
.sub-menu {
display: none;
position: absolute;
top: 100%;
left: 0;
background-color: #fff;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<ul class="menu">
<li class="menu-item">
Home
</li>
<li class="menu-item" onclick="toggleSubMenu(this)">
Products
<ul class="sub-menu">
<li>Product 1</li>
<li>Product 2</li>
<li>Product 3</li>
</ul>
</li>
<li class="menu-item">
About
</li>
</ul>
<script>
function toggleSubMenu(element) {
const subMenu = element.querySelector('.sub-menu');
if (subMenu.style.display === 'block') {
subMenu.style.display = 'none';
} else {
subMenu.style.display = 'block';
}
}
</script>
</body>
</html>
will-change
属性提示浏览器提前优化。领取专属 10元无门槛券
手把手带您无忧上云