標籤:
JavaScript 在事件處理函數中預設傳遞了 event 對象,也就是事件對象。但由於瀏覽器 的相容性,開發人員總是會做相容方面的處理。jQuery 在封裝的時候,解決了這些問題,並且 還建立了一些非常好用的屬性和方法
一.事件對象
事件對象就是 event 對象,通過處理函數預設傳遞接受。之前處理函數的 e 就是 event 事件對象,event 對象有很多可用的屬性和方法,我們在 JavaScript 課程中已經詳細的瞭解 過這些常用的屬性和方法,這裡,我們再示範一次。
//通過處理函數傳遞事件對象
$(‘input‘).bind(‘click‘,function(e){
//接受事件對象參數
alert(e);
});
//通過 event.type 屬性擷取觸發事件名
$(‘input‘).click(function(e){
alert(e.type);
});
//通過 event.target 擷取綁定的 DOM 元素
$(‘input‘).click(function(e){
alert(e.target);
});
//通過 event.data 擷取額外資料,可以是數字、字串、數組、對象
$(‘input‘).bind(‘click‘,123,function(){ //傳遞 data 資料
alert(e.data); //擷取數字資料
});
注意:如果字串就傳遞:‘123‘、如果是數組就傳遞:[123,‘abc‘],如果是對象就傳遞: {user:‘Lee‘,age:100}。數組的調用方式是:e.data[1],對象的調用方式是:e.data.user。
//event.data 擷取額外資料,對於封裝的簡寫事件也可以使用
$(‘input‘).click({user:‘Lee‘, age:100},function(e){
alert(e.data.user);
});
注意:索引值對的鍵可以加上引號,也可以不加;在調用的時候也可以使用數組的方式: alert(e.data[‘user‘]);
//擷取移入到 div 之前的那個 DOM 元素
$(‘div‘).mouseover(function(e){
alert(e.relatedTarget);
});
//擷取移出 div 之後到達最近的那個 DOM 元素
$(‘div‘).mouseout(function(e){
alert(e.relatedTarget);
});
//擷取綁定的那個 DOM 元素,相當於 this,區別與 event.target
$(‘div‘).click(function(e){
alert(e.currentTarget);
});
注意:event.target 得到的是觸發元素的 DOM,event.currentTarget 得到的是監聽元素的 DOM。而 this 也是得到監聽元素的 DOM。
//擷取上一次事件的傳回值
$(‘div‘).click(function(e){
return‘123‘;
});
$(‘div‘).click(function(e){
alert(e.result);
});
//擷取當前的時間戳記
$(‘div‘).click(function(e){
alert(e.timeStamp);
});
//擷取滑鼠的左中右鍵
$(‘div‘).mousedown(function(e){
alert(e.which);
});
//擷取鍵盤的按鍵
$(‘input‘).keyup(function(e){
alert(e.which);
});
//擷取是否按下了 ctrl 鍵,meta 鍵不存在,導致無法使用
$(‘input‘).click(function(e){
alert(e.ctrlKey);
});
//擷取觸發元素滑鼠當前的位置
$(document).click(function(e){
alert(e.screenY+‘,‘+e.pageY+‘,‘ +e.clientY);
});
二.冒泡和預設行為
如果在頁面中重疊了多個元素,並且重疊的這些元素都綁定了同一個事件,那麼就會出現冒泡問題
//HTML 頁面
<div style="width:200px;height:200px;background:red;">
<input type="button"value="按鈕"/>
</div>
//三個不同元素觸發事件
$(‘input‘).click(function(){
alert(‘按鈕被觸發了!‘);
});
$(‘div‘).click(function(){
alert(‘div 層被觸發了!‘);
});
$(document).click(function(){
alert(‘文檔頁面被觸發了!‘);
});
注意:當我們點擊文檔的時候,只觸發文檔事件;當我們點擊 div 層時,觸發了 div 和 文檔兩個;當我們點擊按鈕時,觸發了按鈕、div 和文檔。觸發的順序是從小範圍到大範圍。 這就是所謂的冒泡現象,一層一層往上。
jQuery 提供了一個事件對象的方法:event.stopPropagation();這個方法設定到需要觸發 的事件上時,所有上層的冒泡行為都將被取消。
$(‘input‘).click(function(e){
alert(‘按鈕被觸發了!‘);
e.stopPropagation();
});
網頁中的元素,在操作的時候會有自己的預設行為。比如:右擊文字框輸入地區,會彈 出系統功能表、點擊超連結會跳轉到指定頁面、點擊提交按鈕會提交資料。
$(‘a‘).click(function(e){
e.preventDefault();
});
//禁止提交表單跳轉
$(‘form‘).submit(function(e){
e.preventDefault();
});
注意:如果想讓上面的超連結同時阻止預設行為且禁止冒泡行為,可以把兩個方法同時 寫上:event.stopPropagation()和event.preventDefault()。這兩個方法如果需要同時啟用的時候, 還有一種簡寫方案代替,就是直接 return false
$(‘a‘).click(function(e){
return false;
});
jQuery 事件對象