事件對(duì)象: event
兼容性: 兼容 Chrome IE系列 不兼容FireFox
在FF里: ev 系統(tǒng)傳過(guò)來(lái)的事件
事件 = function(ev){
event 兼容 除了FF
ev 兼容性 FF Chrome IE9+
解決: var oEvent = ev || event;
var oEvent = event || ev; // × 因?yàn)閑vent在FF下報(bào)錯(cuò)
}
var oEvent = ev || event;
事件冒泡:
子元素的事件會(huì)傳遞到父元素,如果父元素有這個(gè)事件扁掸,那就執(zhí)行
如果父元素沒(méi)有這個(gè)事件翘县,再向上找
//阻止冒泡
oEvent.cancelBubble = true;
onkeydown -- 當(dāng)鍵盤(pán)按下的時(shí)候
onkeyup -- 當(dāng)鍵盤(pán)抬起的時(shí)候
事件詳情: var oEvent = ev || event;
keyCode: 是數(shù)字,而且是一些連續(xù)的數(shù)字
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;
阻止默認(rèn)行
return false; 兼容:chrome ff ie9+
針對(duì)低級(jí)瀏覽器:
事件捕獲 obj.setCapture();
事件綁定
綁定:addEventListener('click',fn,false);
解綁:removeEventListener('click',fn,false);
綁定:attachEvent('onclick',fn);
解綁:detachEvent('onclick',fn);
捕獲:事件下沉 和 事件冒泡對(duì)應(yīng)的
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('上');
}
});