日期:2014-05-16  浏览次数:20362 次

模仿鼠标右击菜单
近期要用到鼠标右击事件,所以花了点时间在写这个函数,具体代码我贴在下面,希望各位高手多多指点,也希望大侠们能给我点建议如何做成js封装类,可以通用的函数,这才是我发帖的目的,在此谢过各位指点迷津!
HTML代码:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>testEvent.html</title>

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=GB18030">
    
    <style type="text/css">
     .dd{
     width: 200px;
     height: 200px;
     background: #D4D0C8;
     border-top:2px double #e9e9e9;
     border-left:2px double #e9e9e9;
     border-bottom:2px solid #8E8E8E;
     border-right:2px solid #8E8E8E;
     padding:5px 0 0 15px;
     position: absolute;
     z-index: 999;
     }
     #xx div:hover{
     background: #fff;
     cursor: pointer;
     }
    </style>
<script type="text/javascript" src="testEvent.js"></script>
  </head>
  
  <body>

  </body>
</html>


testEvent.js代码:

document.onmousedown = function(e) {
var e = e || window.event;
var target = e.target || e.srcElement;
if (e.button == 2) {
// alert(document.documentElement.scrollHeight);
document.oncontextmenu = function() {
return false;
};
createDiv(e);
} else {
if (document.getElementById('xx') && target.id != 'xx'
&& target.parentNode.id != 'xx') {
document.getElementById('xx').style.display = 'none';
}
}
};

function createDiv(e) {
var _x = e.clientX || e.pageX, _y = e.clientY || e.pageY;
if (!document.getElementById('xx')) {
publicMethod(_x, _y);
} else {
document.body.removeChild(document.getElementById('xx'));
publicMethod(_x, _y);
}
}
function publicMethod(_x, _y) {
var div = document.createElement('div');
div.id = 'xx';
div.className = 'dd';
div.innerHTML = "<div onclick='run(this)' onmouseover='over(this)' onmouseout='out(this)'>菜单一</div><div onclick='run(this)' onmouseover='over(this)' onmouseout='out(this)'>菜单二</div><div onclick='run(this)' onmouseover='over(this)' onmouseout='out(this)'>菜单三</div><div onclick='run(this)' onmouseover='over(this)' onmouseout='out(this)'>菜单四</div>";
document.body.appendChild(div);
if (_x