Professional JS(13.3.1Event Object in DOM/IE/Cross-Browser/UI&Focus&Mouse and Wheel event[half])

1.The DOM Event Object(续)
+①The stopPropagation()【阻止传播】 method stops the flow of an event through the DOM structure immediately,canceling any further event capturing or bubbling before it occurs.

var btn=document.getElementById('myBtn');
btn.onclick=function(event){
    alert('Clicked');//"Clicked"
};
document.body.onclick=function(){
    alert('Body Clicked');//"Body Clicked"
};



var btn=document.getElementById('myBtn');
btn.onclick=function(event){
    alert('Clicked');   //"Clicked"
    event.stopPropagation();
};
document.body.onclick=function(){
    alert('Body Clicked');   //无效!因为click事件不会传播到document.body
};

+②The eventPhase property aids in(帮助) determining what plase(阶段) of event flow is currently active.If the event handler is called during the capture phase,eventPhase is 1;if the event handler is at the target,eventPhase is 2;if the event handler is during the bubble phase,event phase is 3.Note that even though “at target” occures during the bubbling phase,eventPhase is always 2.

var btn=document.getElementById('myBtn');
btn.onclick=function(event){
    alert(event.eventPhase);   //2---traget
};
document.body.addEventListener('click',function(event){
    alert(event.eventPhase);
},true);   //1----capturing---[false]:bubbling
document.body.onclick=function(event){
    alert(event.eventPhase);  //3---bubbling
}

③The event object exists only while event handlers are still being executed;once all event handlers have been executed,the event object is destroyed.

2.The IE Event Object
+①Since the scope of an event handler is determined by the manner in which it was assigned,the value of this cannot always be assumed be equal to the event target,so it's a good idea to always use event.srcElement instead.

var btn=document.getElementById('myBtn');
//DOM 0级 事件处理程序---this的作用域是所在元素的作用域
btn.onclick=function(){
    alert(window.event.srcElement===this);//true
};
//IE 事件处理程序----this的作用域是全局作用域
btn.attachEvent('onclick',function(){
    alert(event.srcElement===this); //false
});

+②The returnValue property is the equivalent of the DOM preventDefault() method in that it cancels the default behavior of a given event.You need only set returnValue to false to prevent the default action.

var link=document.getElementById('myLink');
link.onclick=function(){
    window.event.returnValue=false;
};

+③The cancelBubble property performs the same action as the DOM stopPropagation() method:it stops the event from bubbling.Since IE 8- don't support the capturing phase,only bubbling is canceled,whereas stopPropagation() stops both capturing and bubbling.

var btn=document.getElementById('myBtn');
btn.onclick=function(){
    alert('Clicked');   //"Clicked"
    window.event.cancelBubble=true;
};
document.body.onclick=function(){
    alert('Body Clicked'); //无效!
};

3.The Cross-Browser Event Object
+①

var EventUtil={
    addHandler:function(element,type,handler){
        if(element.addEventListener){
            element.addEventListener(type,handler,false);
        }else if(element.attachEvent){
            element.attachEvent('on'+type,handler);
        }else{
            element['on'+type]=handler;
        }
    },
    removeHandler:function(element,type,handler){
        if(element.removeEventListener){
            element.removeEventListener(type,handler,false);
        }else if(element.detachEvent){
            element.detachEvent('on'+type,handler);
        }else{
            element['on'+type]=null;
        }
    },
    getEvent:function(event){
        return event ? event : window.event;
    },
    getTarget:function(event){
        return event.target || event.srcElement;
    },
    preventDefault:function(event){
        if(event.preventDefault){
            event.preventDefault();
        }else{
            event.returnValue=false;
        }
    },
    stopPropagation:function(event){
        if(event.stopPropagation){
            event.stopPropagation();
        }else{
            event.cancelBubble=true;
        }
    }
};
/*
假设有一个事件对象传入到事件处理程序中,并将该变量传入这个方法。
在兼容DOM的浏览器中,event变量只是简单地传入和返回,在IE中,
event参数是未定义的(undefined),导致返回window.event.
*/
btn.onclick=function(event){
    event=EventUtil.getEvent(event);
    var target=EventUtil.getTarget(event);
};
//preventDefault()&returnValue=false;
var links=document.getElementById('myLink');
links.onclick=function(event){
    event=EventUtil.getEvent(event);
    EventUtil.preventDefault(event);
};
//stopPropagation()&cancelBubble=true
var btn=document.getElementById('myBtn');
btn.onclick=function(event){
    alert('Clicked');
    event=EventUtil.getEvent(event);
    EventUtil.stopPropagation(event);
};
document.body.onclick=function(event){
    alert('Body Clicked');
};

4.UI Events
+①判断浏览器是否支持”DOM2级和DOM3级事件”定义的事件。

var isSupported=document.implementation.hasFeature('HTMLEvents','2.0');
var isSupported=document.implementation.hasFeature('UIEvent','3.0');//注意是event

+*②The load event is perhaps the most often used event in JS.For the window object,the load events fires when the entire page has been loaded,including all external resources such as images,JavaScript files,and CSS files.You can define an onload event handler in two ways.The first is by using JavaScript.

EventUtil.addHandler(window,'load',function(event){
    alert('Loaded');
});


<img src="rudy.png" id='rudy' onload="alert('Image Loaded.')">

var image=document.getElementById('rudy');
EventUtil.addHandler(image,'load',function(event){
    event=EventUtil.getEvent(event);
    alert(EventUtil.getTarget(event).src);//file:///E:/daily%20life/update/rudy.png
});


//创建一个img元素,并加入document文档中,实现同样的功能
EventUtil.addHandler(window,'load',function(){
    var image=document.createElement('img');
    EventUtil.addHandler(image,'load',function(event){
        event=EventUtil.getEvent(event);
        alert(EventUtil.getTarget(event).src);//file:///E:/daily%20life/update/rudy.png
    });
    document.body.appendChild(image);
    image.src='rudy.png';
});

③第二种方式是为<body>元素添加一个onload特性:<body οnlοad=”alert('Loaded.')”>

④According to DOM Level 2 Events,the load event is supported to fire on ducument,not on window.However,load is implemented on window in all browser for backwards compatibility(向后兼容性).

⑤IE 8- don't generate an event obejct when the load event fires for an image that isn't part of the DOM document.This pertains(适用于) both to <img> elements that are never added to the document and to the Image object.This was fixed in IE 9.

+⑥This example uses the cross-browser EventUtil object to assign the onload event handler to a newly created <script> element.The event object's target is the <script> node in most browsers.IE 8- do not support the load event for <script> elements.

EventUtil.addHandler(window,'load',function(){
    var script=document.createElement('script');
    script.type='text/script';
    EventUtil.addHandler(script,'load',function(event){
        alert('Loaded');
    });
    script.src='example.js';
    document.body.appendChild(script);
});

+⑦IE and Opera support the load event for <link> elements,allowing you to determine when a style sheet has been loaded.As with the <script> node,a style sheet does not begin downloading until the href property has been assigned and the <link> element has been added to the document.

EventUtil.addHandler(window,'load',function(){
    var link=document.createElement('link');
    link.rel='stylesheet';
    link.type='text/css';
    EventUtil.addHandler(link,'load',function(event){
        alert('css loaded.');
    });
    link.href='example.css';
    document.body.appendChild(link);
};

+⑧A companion to the load event,the unload event fires when a document has completely unloaded.The unloaded event typically fires when navigating from one page to another and is most often used to clean up references to avoid memory leaks(内存泄漏).Similar to the load event,an unload event handler can be assigned in two ways.

//方法一:使用JavaScript
EventUtil.addHandler(window,'unload',function(event){
    alert('Unloaded');
});


//方法二:为<body>元素添加一个特性
<!doctype html>
<html>
<head>
    <title>Unload Event Example</title>
</head>
<body onunload="alert('Unloaded')">

</body>
</html>

⑨According to DOM Level 2 Events,the unload event is supposed to fire on <body>,not on window.However,unload is implemented on window in all browsers for backwards compatibility.

+⑩There are some important differences as to when the resize events fire across browsers.IE,Safari,Chrome and Opera fire the resize event as soon as the browser is resized by one pixel and then repeatedly as the user resizing the browser.Firefox fires the resize event only after the user has stopped resizing the browser.Because of these differences,you should avoid computation-heavy code in the event handler for this event,because it will be executed frequently and cause a noticeable slowdown in the browser.The resize event also fires when the browser window is minizied or maximized.

EventUtil.addHandler(window,'resize',function(event){
    alert('Resized');
});

⑪Even though the scroll event occurs on the window,it actually refers to changes in the appropriate page-level element.In standards mode,the changes occur on the <html> element in all browsers except Safari(which still tracks scroll on <body>);In quirks mode,the changes are observable using the scrollLeft and scrollTop of the <body> element.

EventUtil.addHandler(window,'scroll',function(event){
    if(document.compatMode=='CSS1Compat'){    //标准模式下
        alert(document.documentElement.scrollTop);
    }else{                                    //混杂模式下(Safari 3.1-)
        alert(document.body.scrollTop);
    }
})

5.Mouse and Wheel Events
①鼠标事件
a)mousedown:在用户按下了任意鼠标按钮时触发。
b)mouseenter【不会冒泡】:在鼠标光标从元素外部首次移动到元素范围内时触发。IE,Opera,Firefox 9+支持。
c)mouseleave【不会冒泡】:在位于元素上方的鼠标光标移动到元素范围之外时触发。
d)mousemove:当鼠标指针在元素内部移动时重复地触发。
e)mouseout:当鼠标指针位于一个元素上方,然后用户将其移入另一个元素时触发。mouseout包含mouseleave
f)mouseover:当鼠标指针位于一个元素外部,用户将其首次移入另一个元素边界之内时触发。mouseover包含mouseenter
g)mouseup:当用户释放鼠标按钮时触发。

6.Client Coordinates
+①Mouse events all occur at a particular location within the browser viewport.This information is stored in the clientX and clientY properties of the event object.

var div=document.getElementById('myDiv');
EventUtil.addHandler(div,'click',function(event){
    event=EventUtil.getEvent(event);
    alert('Client coordinates:' +event.clientX +',' +event.clientY);
});

7.Page Coordinates
+①When client coordinates give you information about where an event occurred in the viewport,page coordinates tell you where on the page the event occurred via the pageX and pageY properties of the event obejct.

var div=document.getElementById('myDiv');
EventUtil.addHandler(div,'click',function(event){
    event=EventUtil.getEvent(event);
    alert('Page coordinates:' +event.pageX + ',' + event.pageY);
});

+②IE 8- don't support page coordinates on the event object,but you can calculate them using client coordinates and scrolling information(scrollLeft,scrollTop).You need to use the scrollLeft and scrollTop properties on either document.documentElement(in standards mode) or document.body(in quirks mode).

var div=document.getElementById('myDiv');
EventUtil.addHandler(div,'click',function(event){
    event=EventUtil.getEvent(event);
    var pageX=event.pageX;
    var pageY=event.pageY;
    if(pageX===undefined){
        pageX=event.clientX + (document.documentElement.scrollLeft)||
            document.body.scrollLeft);
    }
    if(pageY===undefined){
        pageY=event.clientY + (document.documentElement.scrollTop)||
            document.body.scrollTop);
    }
    alert('Page coordinates: ' +pageX +',' pageY);
});

8.Screen Coordinates
+①Mouse events occur not only in relation to the browser window but also in relation to the entire screen.

var div=document.getElementById('myDiv');
EventUtil.addHandler(div,'click',function(event){
    event=EventUtil.getEvent(event);
    alert('Screen coordinates: ' + event.screenX +','+ event.screenY);
});

9.Modifier Keys
+①Even though a mouse event is primarily triggered(触发) by using the mouse,the state of certain keyboard keys may be important in determining the action to take.The modifier keys Shift,Ctrl,Alt, and Meta are oftens used to alter the behavior of a mouse event.The DOM specifies four properties to indicate the state of these modifier keys:shiftKey,ctrlKey,altKey, and metaKey.

var div=document.getElementById('myDiv');
EventUtil.addHandler(div,'click',function(event){
    event=EventUtil.getEvent(event);
    var keys=new Array();
    if(event.shiftKey){
        keys.push('shift');
    }
    if(event.ctrlKey){
        keys.push('ctrl');
    }
    if(event.artKey){
        keys.push('art');
    }
    if(event.metakey){
        keys.push('meta');
    }
    alert('Keys: '+keys.join(','));
});

②IE 9,【+4】 support all four keys.IE 8- do not support the metaKey property.

10.Related Elements
①This page renders(映射,显示) a single <div> on the page.If the mouse cursor starts over the <div> and the moves outside of it,a mouseout event fires on <div> and the related element is the <body> element.Simultaneously(同时地),the mouseover event firs on <body> and the related element is <div>.

+②The DOM provides information about related elements via the relatedTarget property on the event object.This porperty contains a value only for the mouseover and mouseout events;it is null for all other events.IE 8- don't support the relatedTarget property but offer comparable(类似的) access to the related element using other properties.When the mouseover event fires,IE provides a fromElement property containing the related element;when the mouseout event fires,IE provideds a toElement property containing the related element(IE 9 supports all properties).A cross-browser method to get the related element can be added to EventUtil like this.

var EventUtil={
    //more codes here

    getRelatedTarget:function(event){
        if(event.relatedTarget){
            return event.relatedTarget;
        }else if(event.toElement){
            return event.toElement;
        }else if(event.fromElement){
            return event.fromElement;
        }else{
            return null;
        }
    },

    //more codes here
};

var div=document.getElementById('myDiv');
EventUtil.addHandler(div,'mouseout',function(event){
    event=EventUtil.getEvent(event);
    var target=EventUtil.getTarget(event);
    var relatedTarget=EventUtil.getRelatedTarget(event);
    alert('Moused out of '+target.tagName + 'to ' +relatedTarget.tagName);
});

11.Buttons
+①The DOM button property has the following three possible values:0 for the primary mouse button(左键);1 for th e middle mouse button(usually the scroll wheel button)and 2 for the secondary mouse button(右键).IE 8-也提供了button属性,但两者差别不会一般的大。

var EventUtil={
    //more codes here

    getButton: function(event){
        if(document.implementation.hasFeature('MouseEvents','2.0')){
            return event.button;
        }else{
            switch(event.button){
                case 0:
                case 1:
                case 3:
                case 5:
                case 7:
                    return 0;
                case 4:
                    return 1;
                case 2:
                case 6:
                    return 2;
            }
        }
    },

    //more codes here
};

var div=document.getElementById('myDiv');
EventUtil.addHandler(div,'mousedown',function(event){
    event=EventUtil.getEvent(event);
    alert(EventUtil.getButton(event));
});

②Note that when used with an mouseup event handler,the value of button is the button that was just released.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值