JS技术

javascript鼠标事件总结_Javascript教程(2)

字号+ 作者:H5之家 来源:H5之家 2015-10-01 13:14 我要评论( )

它接受一个哈希参数,都是可选项。哈希的el为要绑定鼠标事件的元素,left为点击左键激发的事件,其他两个类推。用法如下: var el = document.getElementById(mouse); var ex = document.getElementById(explanatio

它接受一个哈希参数,都是可选项。哈希的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;">&nbsp;</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>

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
网友点评