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.οnclick=function(event){
    alert('Clicked');//"Clicked"
};
document.body.οnclick=function(){
    alert('Body Clicked');//"Body Clicked"
};



var btn=document.getElementById('myBtn');
btn.οnclick=function(event){
    alert('Clicked');   //"Clicked"
    event.stopPropagation();
};
document.body.οnclick=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.οnclick=function(event){
    alert(event.eventPhase);   //2---traget
};
document.body.addEventListener('click',function(event){
    alert(event.eventPhase);
},true);   //1----capturing---[false]:bubbling
document.body.οnclick=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.οnclick=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.οnclick=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.οnclick=function(){
    alert('Clicked');   //"Clicked"
    window.event.cancelBubble=true;
};
document.body.οnclick=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.οnclick=function(event){
    event=EventUtil.getEvent(event);
    var target=EventUtil.getTarget(event);
};
//preventDefault()&returnValue=false;
var links=document.getElementById('myLink');
links.οnclick=function(event){
    event=EventUtil.getEvent(event);
    EventUtil.preventDefault(event);
};
//stopPropagation()&cancelBubble=true
var btn=document.getElementById('myBtn');
btn.οnclick=function(event){
    alert('Clicked');
    event=EventUtil.getEvent(event);
    EventUtil.stopPropagation(event);
};
document.body.οnclick=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' οnlοad="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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章