鼠标事件,一般用button来区分鼠标的按键(DOM3标准规定: click事件只能监听左键, 只能通过mousedown和mouseup来判断鼠标键):
1.鼠标左键 button = 0
2.鼠标右键 button = 2
3.鼠标滑轮 button = 1
div.onmousedown = function (e) {
var event = e || window.event;
if(event.button == 2){
console.log('right');
}else if(event.button == 0){
console.log('left');
}
}
解决mousedown和click的之间的冲突 (利用事件发生时间来判断 点击事件时间短)
var key = false;//设置了一个标志 false为点击事件 ture为鼠标移动事件
var firstTime = 0;
var lastTime = 0;
div.onclick = function() {
if(key){
console.log('click');
key = false;
}
}
div.onmousedown = function() {
firstTime = new Date().getTime();
console.log('mouseDown');
}
div.onmouseup = function() {
console.log('mouseUp');
//鼠标抬起后 记录时间 超过200ms就是移动事件
lastTime = new Date().getTime();
if( (lastTime - firstTime) <){
key = true;
}
}