創(chuàng)建事件、觸發(fā)事件

fastclick源碼中涉及到自創(chuàng)建自定義事件,相關(guān)基礎(chǔ)知識(shí)要準(zhǔn)備:

首先,最簡(jiǎn)單的:** 創(chuàng)建一個(gè)事件并觸發(fā):**

// 第一種方法,但是已經(jīng)不推薦了,不過(guò)fastclick上用的這種
// Create the event.
var event = document.createEvent('Event');

// Define that the event name is 'build'.
event.initEvent('build', true, true);

// Listen for the event.
elem.addEventListener('build', function (e) {
  // e.target matches elem
}, false);

// target can be any Element or other EventTarget.
elem.dispatchEvent(event);

//第二種,直接用構(gòu)造函數(shù)
var event = new Event('build');

// Listen for the event.
elem.addEventListener('build', function (e) { ... }, false);

// Dispatch the event.
elem.dispatchEvent(event);

相關(guān)連接見(jiàn):
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

fastclick中的真實(shí)做法

fastclick中有一個(gè)sendclick原型方法,目的是將模擬觸發(fā)targetElement的click事件。

touch = event.changedTouches[0];

// Synthesise a click event, with an extra attribute so it can be tracked
clickEvent = document.createEvent('MouseEvents');
/*2*/ clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
/*3*/ clickEvent.forwardedTouchEvent = true;
targetElement.dispatchEvent(clickEvent);

第三行的forwardedTouchEvent是給這個(gè)事件加的標(biāo)簽,方便跟蹤。
第二行的方法參數(shù)太多,完全可以寫(xiě)成更加易讀的形式:

clickEvent.initMouseEvent(this.determineEventType(targetElement), //type
    true, //canBubble
    true, //canCanceled
    window, //view
    1, //detail: 點(diǎn)擊了幾次
    touch.screenX, //screenX 
    touch.screenY, //screenY
    touch.clientX,  
    touch.clientY, 
    false, //ctrlKey,
    false, //altKey
    false, //shiftKey
    false, //metaKey
    0, //mouseEvent.button 0:鼠標(biāo)左鍵 1:鼠標(biāo)中鍵 2:鼠標(biāo)右鍵 
    null //相關(guān)節(jié)點(diǎn),在鼠標(biāo)點(diǎn)擊事件中設(shè)為null就好了,在mousein等事件中有用
);

相關(guān)連接:
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/initMouseEvent

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 前端知識(shí)體系http://www.cnblogs.com/sb19871023/p/3894452.html 前端...
    秋風(fēng)喵閱讀 12,751評(píng)論 7 163
  • 一年又過(guò)去一半了 銀行卡還是沒(méi)怎么有太大的變化 生活各處依然如此 除了日子在一天天的過(guò) 工作沒(méi)了激情,沒(méi)有存在感,...
    袁慧_3c1b閱讀 245評(píng)論 0 0
  • 你對(duì)一個(gè)人有了欲望,那叫喜歡;你為一個(gè)人忍住了欲望,那叫愛(ài)。愛(ài)是懂得珍惜,懂得克制。我忍住了,我做到了,我非常珍惜...
    一生懂你閱讀 238評(píng)論 0 0
  • 今天是今日有所思第95天。 人工智能來(lái)了!人工智能會(huì)取代很多人類原本從事的工作,程式化、重復(fù)性、僅靠記憶和練習(xí)就可...
    荒原蒼狼閱讀 159評(píng)論 0 0
  • 今天無(wú)意中從一個(gè)朋友那兒知道了這個(gè)簡(jiǎn)書(shū),從此我可以把自己的孤獨(dú)寫(xiě)進(jìn)這里,而不又影響現(xiàn)實(shí)中的生活。生活的茍且...
    詹詹zmz閱讀 190評(píng)論 0 1

友情鏈接更多精彩內(nèi)容