本文實(shí)例為大家分享了JavaScript模擬鼠標(biāo)右鍵菜單的具體代碼,供大家參考,具體代碼如下
具體代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>右鍵菜單</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#menu{
width: 254px;
/*background-color: #ccc;*/
font-size: 12px;
position: fixed;
top: 0px;
left: 0px;
/*height: 240px;*/
/*padding-left: 26px;*/
padding-top: 2px;
border:1px solid #ccc;
display: none;
}
#menu li{
list-style: none;
line-height: 25px;
margin-left: -1px;
padding-left: 26px;
}
#menu li:hover{
background-color: #4281f4;
color: #fff;
}
</style>
</head>
<body>
<ul id="menu">
<li>返回(B)</li>
<li>前進(jìn)(F)</li>
<li>從新加載(R)</li>
<li>另存為(A)</li>
<li>打印(P)</li>
<li>查看網(wǎng)頁(yè)源代碼(V)</li>
<li>查看網(wǎng)頁(yè)信息(I)</li>
<li>審查元素(N)</li>
</ul>
<script type="text/javascript">
var menu = document.getElementById("menu");
document.oncontextmenu =function(e){
var e = e ||window.event;//兼容
console.log(e.clientX,e.clientY);
console.log(e);
//單擊顯示div
menu.style.display = "block";
//設(shè)置定義
//判斷鼠標(biāo)坐標(biāo)是否大于視口寬度-塊本身寬度
var cakLeft = (e.clientX > document.documentElement.clientWidth - menu.offsetWidth)?(document.documentElement.clientWidth - menu.offsetWidth):e.clientX;
var cakTop = (e.clientY > document.documentElement.clientHeight - menu.offsetHeight)?(document.documentElement.clientHeight - menu.offsetHeight):e.clientY;
menu.style.left = cakLeft + "px";
menu.style.top = cakTop + "px";
return false;
}
menu.onclick = function(e) {
var e = e || window.event;
e.cancelBubble = true;
//阻止冒泡。
}
document.onclick = function() {
menu.style.display = "none";
}
</script>
</body>
</html>
希望本文所述對(duì)大家學(xué)習(xí)javascript程序設(shè)計(jì)有所幫助。