JS基础学习四:绑定事件

[b]添加事件[/b]
IE: attachEvent
Other: addEventListener

var button = document.getElementById("buttonId");
if(button.addEventListener){
button.addEventListener("click",eventFunction,false);
}else if(button.attachEvent){
button.attachEvent("onclick",eventFunction);
}


[b]删除事件[/b]
IE: detachEvent
Other: removeEventListener

[b]事件冒泡机制[/b]
IE: 事件从它发生的地方被触发,然后向DOM结构的上层冒泡
Other: 事件先向下沉入到目标元素,再向上冒泡
addEventListener( , ,[true|false])
[list]
[*]true: 向下沉入时截获事件
[*]false: 向上冒泡时截获事件
[/list]

[b]停止事件冒泡: [/b]
IE: window.event.cancelBubble=false;
Other: e.stopPropagation();

[b]实验的例子:[/b]

function bindEvent() {
var button = document.getElementById("buttonId");
if (button.addEventListener) {
alert("Other browser");
//button.addEventListener("click",showEvent,false);
//button.addEventListener("click",showEvent2,false);
button.addEventListener("click", showEvent, true);
button.addEventListener("click", showEvent2, true);
} else if (button.attachEvent) {
alert("IE browser");
button.attachEvent("onclick", showEvent);
button.attachEvent("onclick", showEvent2);
}
}

function removeEvent() {
var button = document.getElementById("buttonId");
if (button.removeEventListener) {
alert("Other browser");
//button.removeEventListener("click",showEvent,false);
button.removeEventListener("click", showEvent, true);
} else if (button.detachEvent) {
alert("IE browser");
button.detachEvent("onclick", showEvent);
}
}

function showEvent(e) {
if (window.event != undefined) {
window.event.cancelBubble = true;
} else if (e.stopPropagation) {
e.stopPropagation();
}
alert("Event here!");
}

function showEvent2() {
alert("Other event here!");
}

function divEvent() {
alert("Div Event");
}


<div onclick="divEvent()">
<input type="button" id="buttonId" value="showEvent"/>
</div>


[b]键盘事件[/b]
window.onload=function(){
//绑定键盘事件
document.onkeydown=showkey;
}

function showkey(e){
var key;
if(window.event)
key= window.event.keyCode;
else
key= e.keyCode;

alert(String.fromCharCode(key));
}


[b]鼠标事件[/b]
获取mouse的位置
IE: clientX,clientY
Other: pageX, pageY
document.onmouseover= showPosition;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值