关于javascript:鼠标左右键区分点击和拖拽和键盘事件

onmousedown 事件有个 event.button 能够返回一个数值,依据数值判断获得用户按了那个鼠标键
event.button==0 默认。没有按任何按钮。
event.button==1 鼠标左键
event.button==2 鼠标右键
event.button==3 鼠标左右键同时按下
event.button==4 鼠标中键
event.button==5 鼠标左键和中键同时按下
event.button==6 鼠标右键和中键同时按下
event.button==7 所有三个键都按下

兼容IE的写法:
e = e || window.event;

鼠标左右键的辨别

 // 如何辨别鼠标的左右键0/1/2
 // 在源对象里
 // button=0左键
 // button=2右键
document.onmousedown = function (e) {
   if(e.button==2){
       console.log('right');
   }else if(e.button==0){
    console.log('left')
   }
 }

css中的hover 就是用js封装的,其中利用了

div.onmouseenter=function(){
       div.style.background='yellow'
   }
   div.onmouseleave=function(){
       div.style.background="green"
   }
//click事件只能监听左键,只能通过mousedown和mouseup来判断鼠标键     

利用工夫戳来辨别客户是要点击还是拖拽

var firstTime = 0;
var lastTime = 0;
var key = flase;
document.onmousedown = function () {
  firstTime = new Date().getTime();
}
document.onmouseup = function () {
  lastTime = new Date().getTime();
  if(lastTime - firstTime < 300){
      key = true;//小于300就是点击,大于300就是别的,想干嘛干嘛
  }
}
document.onclick = function () {
  if (key) {
      console.log("click")
      key = flase;
  }
}

键盘事件
一个小的demo能够感受一下 keydown>keypress>keyup
keydown能够响应任何键,keypress只能响应字符类按键

document.onkeydown = function () {
        console.log('keydown')
    }
    document.onkeypress = function () {
        console.log('keypress')
    }
    document.onkeyup = function () {
        console.log('keyup')
    }
document.onkeydown = function (e) {
        console.log(e)
    }
    document.onkeypress = function (e) {
        console.log(e)
    }
    document.onkeyup = function (e) {
        console.log(e)
    }

keypress 辨别大小写字母,keyCode的值不一样,然而keydown和keyup不辨别大小写字母
操作类按键只能用keydown


对于如何把ASSCII码转换成字符

document.onkeypress = function (e) {
        console.log(String.fromCharCode(e.charCode))
    }

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理