一、树形菜单
<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>Document</title>
<link rel="stylesheet" href="./font/iconfont.css">
<link rel="stylesheet" href="./font/demo.css">
<style>
ul li{
list-style-type: none;
}
</style>
</head>
<body>
<ul>
<li><i class="iconfont icon-xiajiantou"></i>1 课程大纲
<ul style="display: block;">
<li>2.1 事件概述</li>
<li>2.2 事件对象</li>
</ul>
</li>
<li><i class="iconfont icon-xiajiantou"></i>2 课程内容
<ul style="display: block;">
<li>2.1 事件概述</li>
<li>2.2 事件对象</li>
<li>2.3 事件操作</li>
</ul>
</li>
<li><i class="iconfont icon-xiajiantou"></i>3 事件特效
<ul style="display: block;">
<li>2.1 事件概述</li>
<li>2.2 事件对象</li>
</ul>
</li>
</ul>
<script>
// 让标签加载完成后执行
window.onload = function() {
//获取多个li
var _lis = document.getElementsByTagName("li")
for (var i = 0; i < _lis.length; i++) {
//添加点击事件
_lis[i].onclick = function (e) {
//获取事件对象
var e = e || window.event;
if(e.stopPropagation) {
e.stopPropagation()
}else {
e.cancelBubble = true
}
//获取子菜单
var children = this.children
if (children.length > 0) {
//存在子菜单,获取唯一的子菜单和i
var child = children[1]
var _i = children[0]
//判断行内样式
if(child.style.display === "block") {
child.style.display = "none"
_i.className = 'iconfont icon-youjiantou'
}else {
child.style.display = "block"
_i.className = 'iconfont icon-xiajiantou'
}
}
}
}
}
</script>
</body>
</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>Document</title>
<style>
* { margin : 0 ;
padding : 0 ;
box-sizing : border-box ;
}
#menu {
transition : all .2s ;
position : absolute ;
width : 0px ;
height : 0px ;
opacity : 0 ;
background-color : #eff1f1 ;
box-shadow : #888 2px 2px 0 ;
display : flex ;
flex-direction : column ;
justify-content : space-between ;
list-style : none ;
border-radius : 5px ;
overflow : hidden ;
}
#menu li {
text-align : center ;
cursor : pointer ;
height : 55px ;
line-height : 55px ;
}
#menu li:hover{
background : #333 ;
color : white ;
}
</style>
</head>
<body>
<ul id="menu">
<li>上一章</li>
<li>下一章</li>
<li>返回目录</li>
<li>刷新</li>
<li>返回首页</li>
</ul>
<script>
var _menu = document.getElementById("menu")
//鼠标右键单击事件
//document 网页文档 根标签
//oncontextmenu事件:鼠标右键事件
document.oncontextmenu = function (e) {
//阻止鼠标右键默认行为
var e = e || window.event
if(e.preventDefault) {
e.preventDefault()
}else {
e.returnValue = false
}
//显示自定义菜单
_menu.style.height = "300px"
_menu.style.width = "200px"
_menu.style.opacity = 1
_menu.style.left = e.clientX + "px"
_menu.style.top = e.clientY + "px"
}
//空白处点击左键,自定义菜单消失
document.onclick = function () {
//隐藏自定义菜单
_menu.style.height = "0px"
_menu.style.width = "0px"
_menu.style.opacity = 0
}
</script>
</body>
</html>