它接受一个哈希参数,都是可选项。哈希的el为要绑定鼠标事件的元素,left为点击左键激发的事件,其他两个类推。用法如下:
var el = document.getElementById("mouse");
var ex = document.getElementById("explanation");
var left = function(){
ex.innerHTML = "左键被按下";
}
var right = function(){
ex.innerHTML = "右键被按下";
}
mouseEvent({el:el,left:left,middle:null,right:right});
<div id="mouse2" style="width:500px;height:200px;background:#E8FFE8;border:2px solid #336699;">
请在这里点击,测试左中右鼠标键绑定函数
</div>
<br />
<div id="explanation2" style="width:500px;border:2px solid #336699;"> </div>
<script type="text/javascript">
var mouseEvent = function(){
var arg = arguments[0],
el = arg.el || document,
leftfn = arg.left || function(){},
rightfn = arg.right || function(){},
middlefn = arg.middle || function(){},
buttons = {};
el.onmousedown = function(e){
e = e || window.event;
if(!+"\v1"){
switch(e.button){
case 1:buttons.left = true; break;
case 2:buttons.right = true; break;
case 4:buttons.middle = true; break;
}
}else{
switch(e.which){
case 1:buttons.left = true;break;
case 2:buttons.middle = true; break;
case 3:buttons.right = true;break;
}
}
if(buttons.left){
leftfn();
}else if(buttons.middle){
middlefn();
}else if(buttons.right){
rightfn();
}
buttons = {
"left":false,
"middle":false,
"right":false
};
}
}
var checkeventbutton = function(){
var el = document.getElementById("mouse2");
var ex = document.getElementById("explanation2");
var left = function(){
ex.innerHTML = "左键被按下";
}
var middle = function(){
ex.innerHTML = "中键被按下";
}
var right = function(){
ex.innerHTML = "右键被按下";
}
mouseEvent({el:el,left:left,middle:middle,right:right});
}
window.onload = function(){
checkeventbutton();
};
</script>