自定义菜单(鼠标右键 移入 移除 事件)示例
2025年4月30日大约 2 分钟
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自定义菜单右键移入移除事件</title>
<style type="text/css" rel="stylesheet">
*
{
margin:0px;
padding:0px;
}
#uls
{
width:80px;
height:auto;
border:solid 1px blue;
position:absolute;
top:0px;
left:0px;
display:none;
}
#uls li
{
width:80px;
height:30px;
border-bottom:solid 1px #eee;
text-align:center;
list-style:none;
line-height:30px;
}
#uls li a
{
text-decoration:none;
color:orange;
}
/*第二种修改方法*/
#uls .cur
{
background:#c81623;
}
</style>
</head>
<body>
<ul id='uls'>
<li><a href=''>剪切</a></li>
<li><a href=''>复制</a></li>
<li><a href=''>粘贴</a></li>
<li><a href=''>查看</a></li>
<li><a href=''>全选</a></li>
</ul>
<script type="text/javascript">
//获取对象
var uls=document.getElementById('uls');
//右键事件
window.oncontextmenu=function(e)
{
//获取x和y的坐标
var x=e.clientX;
var y=e.clientY;
//把获取的元素的x,y的值给usl元素的left和top
uls.style.top=y+'px';
uls.style.left=x+'px';
//隐藏出现
uls.style.display='block';
//阻止默认
return false;
}
//单击事件
window.onclick=function()
{
//单击隐藏
uls.style.display='none';
}
//鼠标移入事件 (每个菜单变色)
var lis=document.getElementsByTagName('li');
for (var i = 0; i < lis.length; i++) {
//鼠标移入事件
lis[i].onmouseover=function()
{
//设置背景颜色
//第一种方法
//this.style.background='#c81623';
//第二种方法 适合多个元素的操作
//this.setAttribute('class','cur');
//第三种方法
this.className='cur';
//获取每个li的子级
var childs=this.firstElementChild;
//修改字体颜色(因为在a标签中 所以需要获取子级)
//(下面操作同样可以用上述三种办法操作!)
childs.style.color='white';
//改变鼠标样式
childs.style.cursor='default';
//增加下划线
childs.style.textDecoration='underline';
}
//鼠标移除事件
lis[i].onmouseout=function()
{
//清空背景色
//第一种方法
//this.style.background='';
//第二种方法 添加类 适合多个元素的操作
//this.setAttribute('class','');
//或者
//this.removeAttribute('class');
//第三种方法
this.className='';
//获取每个li的子级
var childs=this.firstElementChild;
childs.style.color='orange';
childs.style.textDecoration='none';
}
};
</script>
</body>
</html>