DOM事件

1 DOM事件

1.1 什么是DOM事件

点击一个DOM元素,在键盘上按下一个键,输入框输入内容,页面加载完成,这些动作都会触发一系列的事件。

1.2 事件流

事件流:capture phase(w-p) --> target phase(p-a-p) --> bubble phase(p-w);

事件流

1.3 事件注册

/* 事件注册 */
/* eventTarget.addEventListener(type,listener[,useCapture]) */
var elem = document.getElementById("div1");
var clickHandler = function(event){
    //to do
}
//下面两种方法二选一即可
elem.addEventListener('click',clickHandler,false);
elem.onclick = clickHandler;
/* 事件注册兼容IE6,7,8 */
var addEvent = document.addEventListener?
    function(elem,type,listener,useCapture){
        elem.addEventLitener(type,listener,useCapture);
    } :
    function(elem,type,listener,useCapture){
        elem.attachEvent('on'+type,listener);
    };

/* 取消事件注册 */
/* eventTarget.removeEventListener(type,listener[,useCapture]) */
elem.removeEventListener('click',clickHandler,false);
elem.onclick = null;
/* 取消事件注册兼容IE6,7,8 */
var delEvent = document.removeEventListener?
    function(elem,type,listener,useCapture){
        elem.removeEventListener(type,listener,useCapture);
    } :
    function(elem,type,listener,useCapture){
        elem.detachEvent('on'+type,listener);
    };

1.4 事件触发

/* eventTarget.dispatchEvent(type) */
//注意:首先要定义事件,然后才能触发
var click = new Event('click');
elem.dispatchEvent('click');
/* 兼容IE6,7,8 */
/* eventTarget.fireEvent(type) */???

1.5 事件对象

var elem = document.getElementById("div1");
var clickHandler = function(event){
    //to do
}
elem.addEventListener('click',clickHandler,false);
---
/* 兼容低版本IE浏览器 */
var elem = document.getElementById("div1");
var clickhandler = function(evnt){
    event = event||window.event;
    //to do
}
addEvent(elem,'click',clickHandler,false);
  • 事件对象的属性
    • type
    • target(srcElement)
    • currentTarget
  • 事件对象的方法
    • stopPropagation
    • preventDefault
    • stopImmediatePropagation

阻止事件传播

event.stopPropagation();//W3C
event.cancelBubble=true;//IE
event.stopImmediatePropagation();//W3C

默认行为

Event.preventDefault();//W3C
Event.returnValue=false;//IE

//在function函数中使用
var clickHandler = function(event){
    event.preventdefault();
    //todo
};

2 事件分类

事件分类

2-1 鼠标事件

MouseEvent

事件类型 是否冒泡 元素 默认事件 元素例子
click yes Element focus/activation div
dbclick yes Element focus/activation/selection div
mousedown yes Element drag/scroll/text selection div
mousemove yes Element None div
mouseout yes Element None div
mouseover yes Element None div
mouseup yes Element context menu div
mouseenter yes Element None div

MouseEvent对象

  • 属性
    • clientX,clientY (鼠标指针在浏览器页面上的位置)
    • screenX,screenY (鼠标指针在电脑屏幕上的位置)
    • ctrlKey,shiftKey,altKey,metaKey

MouseEvent顺序

  • 从元素A上方移过
    • mousemove->mouseover(A)->mouseenter(A)->mousemove(A)->mouseout(A)-mouseleave(A)
  • 点击元素
    • mousedown->[mousemove]->mouseup->click

Mouse例子:拖拽div

/* html */
<div id="bA">
    <div id="bAm"></div>
</div>
/* css */
#bA{
    border:1px solid #ff00ff;
    height:40px;
    position:relative;
}
#bAm{
    border:1px solid #00ffff;
    width:20px;
    height:20px;
    background-color:red;
    margin:5px;
    position:absolute;
    top:0px;
    left:0px;
}
/* js */
var elemb455a = document.getElementById("bAm");
var clientX,clientY,moving;
var mouseDownHandler = function(event){
    startX = event.clientX;
    startY = event.clientY;
    moving = !0;
    elemb455a.addEventListener('mousemove',mouseMoveHandler,false);
    elemb455a.addEventListener('mouseup',mouseUpHandler,false);
};
var mouseMoveHandler = function(event){
    if(!moving) return;
    var newClientX = event.clientX,
        newClientY = event.clientY;
    var left = parseInt(window.getComputedStyle(elemb455a).left)||0;
    var top = parseInt(window.getComputedStyle(elemb455a).top)||0;
    elemb455a.style.left =left + (newClientX-startX)+'px';
    elemb455a.style.top =top + (newClientY-startY)+'px';
    startX = newClientX;
    startY = newClientY;
};
var mouseUpHandler = function(event){
    moving = !1;
    elemb455a.removeEventListener('mousemove',mouseMoveHandler,false);
};
elemb455a.addEventListener('mousedown',mouseDownHandler,false);

2-2 滚轮事件

事件类型 是否冒泡 元素 默认事件 元素例子
wheel yes Element scroll or zoom,document div
  • 滚轮事件属性
    • deltaMode
    • deltaX
    • deltaY
    • deltaZ

2-3 FocusEvent

事件类型 是否冒泡 元素 默认事件 元素例子
blur no window,element None window,input
fucus no window,element None window,input
focusin yes window,element None window,input
focusout yes window,element None window,input
/* 使用focusevent来改变input输入文字的颜色 */
//html
<div id="obj">
    <input type="text" name="checkfocus" placeholder="focusEvent">
</div>

//js
var obj = document.querySelector('#obj').firstElementChild;
console.log(obj);
var focusHandler = function(){
    obj.setAttribute('style','border-color : red');
}
var blurHandler = function() {
    obj.setAttribute('style','border-color: green');
}
obj.addEventListener('focus',focusHandler,false);
obj.addEventListener('blur',blurHandler,false);
  • 属性
    • relatedTarget

2-4 输入事件

事件类型 是否冒泡 元素 默认事件 元素例子
beforeinput yes element update DOM,Element input
input yes element None input
  • 兼容低版本IE
    • onpropertychange
/* 使用input事件来控制输入框的颜色 */
//html
<div id="obj">
    <input type="text" name="input" placeholder="inputEvent">
</div>

//js
var input = document.getElementsByTagName('input')[0];
console.log(input);
var inputHandler = function(event){
    input.setAttribute('style','border-color: red');
}
input.addEventListener('input',inputHandler,false);

2-5 键盘事件

事件类型 是否冒泡 元素 默认事件 元素例子
keydown yes element beforeinput/input
focus/blur
activation
input,div
keyup yes element None div,input
  • 属性
    • key
    • code
    • ctrlKey,shiftKey,altKey,metaKey
    • repeat
    • keycode(艾斯克码)
    • charCode(艾斯克码)
    • which(艾斯克码)
/* 使用键盘事件来控制div背景 */
//html
<div id="obj">
    <input type="text" name="keyevent" id="keyEvent">
</div>

//js
var obj = document.getElementById('obj');
var keydownHandler = function(event) {
    console.log(event.keyCode);
    if(event.keyCode == 13) {
        obj.setAttribute('style',"background-color:green");
    }
}
obj.addEventListener('keydown',keydownHandler,false);

2-6 event

事件类型 是否冒泡 元素 默认事件 元素例子
load no window,Document,element None window,image,iframe
unload no window,document,element None window
error no window,document,element None window,image
select no element None input,textarea
abort no window,element None window,image
/* 用load来实现一个动画 */
//html
<div id="obj">
    <img src="./DOMbasic/res/git.jpg" id="aim">
</div>
//css
#obj {
    position: relative;
    width: 100%;
    height: 100px;
    background: #770000;
}
#aim {
    position: absolute;
    width: 60px;
    height: 60px;
    left: 0px;
    top: 0px;
    background-color: #007700;
    margin: 20px;
    transition: left 5s ease 3s;
}
//js
var aim = document.getElementById('aim');
console.log(aim);
var loadHandler = function(event) {
    event = event||window.event;
    aim.setAttribute('style','left:1000px');
};

aim.addEventListener('load',loadHandler,false);

2-7 window

  • window
    • load
    • unload
    • error
    • abort
  • image
    • load
    • error
    • abort
<img alt="photo" src="http://www.luwanlin.com/imgs/yoho.jpg" onerror="this.src='http://www.luwanlin.com/imgs/opps.gif'">

//html
<div id="obj">
    <img src="res/error.jpg" width="50px" height="50px" alt="error.jpg">
</div>
//js
var img = document.getElementsByTagName('img')[0];
img.addEventListener('error',function(event){
    this.src = './DOMbasic/res/zhm.jpg';
},false);

2-8 UIEvent

事件类型 是否冒泡 元素 默认事件 元素例子
resize no window,element None window,iframe
scroll no/yes document,element None document,div

3 事件代理

/* 将li的事件注册到ul上面 */
<ul>
    <li></li>
    <li></li>
</ul>
---
//使用父元素代理子元素input中的select事件
//html
<div id="obj">
    <input type="text" name="">
</div>
//js
var obj = document.querySelector('#obj');
obj.addEventListener('select',function(event){
    alert('use event agent!');
},false);
posted @ 2021-01-13 23:14  格一  阅读(246)  评论(0编辑  收藏  举报