事件对象: event
兼容性: 兼容 Chrome IE系列 不兼容FireFox
在FF里: ev 系统传过来的事件
事件 = function(ev){
event 兼容 除了FF
ev 兼容性 FF Chrome IE9+
解决: var oEvent = ev || event;
var oEvent = event || ev; // × 因为event在FF下报错
}
var oEvent = ev || event;
事件冒泡:
子元素的事件会传递到父元素,如果父元素有这个事件,那就执行
如果父元素没有这个事件,再向上找
//阻止冒泡
oEvent.cancelBubble = true;
onkeydown -- 当键盘按下的时候
onkeyup -- 当键盘抬起的时候
事件详情: var oEvent = ev || event;
keyCode: 是数字,而且是一些连续的数字
A 65
B 66
a 97
0 48
1 49
2 50
上 38
下 40
左 37
右 39
空格 32
回车 13
ctrl 17
alt 18
shift 16
退格 8
组合:
oEvent.ctrlKey;
oEvent.altKey;
oEvent.shiftKey;
阻止默认行
return false; 兼容:chrome ff ie9+
针对低级浏览器:
事件捕获 obj.setCapture();
事件绑定
绑定:addEventListener('click',fn,false);
解绑:removeEventListener('click',fn,false);
绑定:attachEvent('onclick',fn);
解绑:detachEvent('onclick',fn);
捕获:事件下沉 和 事件冒泡对应的
function addEvent(obj,sEv,fn){
if(obj.addEventListener){
obj.addEventListener(sEv,fn,false);
}
else{
obj.attachEvent('on'+sEv,fn)
}
}
拖拽:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{margin:0; padding:0;}
#div1{
width: 100px;
height: 100px;
background: red;
position: absolute;
left:200px;
top:200px;
}
</style>
<script>
window.onload = function(){
var oDiv = document.getElementById('div1');
oDiv.onmousedown = function(ev){
var oEvent = ev || event;
var disX = oEvent.clientX - oDiv.offsetLeft;
var disY = oEvent.clientY - oDiv.offsetTop;
document.onmousemove = function(ev){
var oEvent = ev || event;
var l = oEvent.clientX - disX;
var t = oEvent.clientY - disY;
if(l <= 100){
l = 0;
}
if (l >= (document.documentElement.clientWidth - oDiv.offsetWidth-100)){
l = document.documentElement.clientWidth - oDiv.offsetWidth;
}
if(t <= 100){
t = 0;
}
if(t >= (document.documentElement.clientHeight - oDiv.offsetHeight-100)){
t = document.documentElement.clientHeight - oDiv.offsetHeight;
}
oDiv.style.left = l + 'px';
oDiv.style.top = t + 'px';
};
document.onmouseup = function(){
document.onmousemove = null;
document.onmouseup = null;
oDiv.releaseCapture && oDiv.releaseCapture();
};
oDiv.setCapture && oDiv.setCapture();
return false;
};
};
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
滚轮事件:
function addEvent(obj,sEv,fn){
if(obj.addEventListener){
obj.addEventListener(sEv,fn,false);
}
else{
obj.attachEvent('on'+sEv,fn);
}
}
function addWheel(obj,fn){
function wheel(ev){
var oEvent = ev || event;
var bDown = oEvent.wheelDelta ? oEvent.wheelDelta>0 : oEvent.detail>0;
fn && fn(bDown);
}
if(window.navigator.userAgent.toLowerCase().indexOf('firefox') != -1){
addEvent(document,'DOMMouseScroll',wheel)
}else{
addEvent(document,'mousewheel',wheel)
}
}
addWheel(document,function(bDown){
if(bDown){
alert('下');
}
else{
alert('上');
}
});