h5中多级联动菜单怎么写
时间: 2024-12-23 11:26:04 浏览: 5
基于mui写的H5移动端全国地区三级联动菜单
在HTML5中实现多级联动菜单通常涉及到JavaScript、CSS以及可能的Ajax技术。以下是一个简单的例子:
```html
<!DOCTYPE html>
<html lang="zh">
<head>
<style>
/* CSS样式 */
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown:hover .dropdown-content {
display: block;
}
</style>
</head>
<body>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">一级菜单
<i class="fa fa-caret-down"></i>
</button>
<div id="myDropdown" class="dropdown-content">
<a href="#">二级选项1</a>
<a href="#">二级选项2</a>
<!-- 这里可以添加更多二级子菜单 -->
<a href="#" onclick="myFunction2(this)">三级联动</a>
</div>
</div>
<script>
// JavaScript函数
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function myFunction2(e) {
var dropdown = e.parentElement.querySelector('.dropdown-content');
var x = e.clientX;
var y = e.clientY;
var width = dropdown.offsetWidth;
var height = dropdown.offsetHeight;
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
if (x + width > windowWidth || y + height > windowHeight) {
dropdown.style.left = 'auto';
dropdown.style.top = 'auto';
dropdown.style.right = '0';
} else {
dropdown.style.right = e.pageX + 'px';
dropdown.style.top = e.pageY + 'px';
}
}
// 防止悬停时菜单关闭
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>
</body>
</html>
```
这个示例中,点击一级菜单会显示下拉列表,再次点击或鼠标离开下拉列表时菜单消失。当选择“三级联动”选项时,二级菜单会固定在所选元素旁边展开。
阅读全文