<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body{
font-size:16px;
}
ul{
list-style:none;
margin:0;
padding:0;
}
a{
text-decoration:none;
color:#333;
}
.contextmenu{
width:200px;
border:1px solid #999;
box-shadow: 3px 3px 3px #ccc;
background: #fff;
position: absolute;
top:10px;
left:10px;
display: none;
}
.contextmenu li{
height:38px;
line-height:38px;
}
.contextmenu li a{
display:block;
padding:0 20px;
}
@media print{
.contextmenu{
display: none;
opacity:0;
}
}
</style>
</head>
<body>
<h1>自定义右键菜单 -- onmosueover onmosueout</h1>
<hr>
<div class="contextmenu" id="context">
<ul>
<li><a href="#">复制</a></li>
<li><a href="#">粘贴</a></li>
<li><a href="#">剪切</a></li>
<li><a href="">刷新(F5)</a></li>
<li><a href="#" onclick="window.print()">用快播打开</a></li>
</ul>
</div>
<script>
document.oncontextmenu = function(env){
//获取事件对象
var e = env || window.event;
//获取 菜单元素
var context = document.getElementById('context');
//让菜单显示
context.style.display = "block";
//获取窗口的大小
var w = window.innerWidth;
var h = window.innerHeight;
//获取鼠标的坐标
var x = e.clientX;
var y = e.clientY;
//改变菜单的位置
context.style.left = Math.min(w - 202, x) + 'px';
context.style.top = Math.min(h - 192, y)+'px';
return false;
}
document.onclick = function(){
document.getElementById('context').style.display = "none";
}
//获取所有li集合
var lis = document.getElementById('context').getElementsByTagName('li');
//给每个li绑mouseover 事件
for (var i = 0; i < lis.length; i ++) {
lis[i].onmouseover = function(){
this.style.backgroundColor = "#ddd";
document.body.style.backgroundColor = "rgb("+(Math.floor(Math.random() * 256))+","+(Math.floor(Math.random() * 256))+","+(Math.floor(Math.random() * 256))+")";
}
lis[i].onmouseout = function(){
this.style.backgroundColor = "#fff";
}
}
</script>
</body>
</html>
网友评论