fastclick源码中涉及到自创建自定义事件,相关基础知识要准备:
首先,最简单的:** 创建一个事件并触发:**
// 第一种方法,但是已经不推荐了,不过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);
//第二种,直接用构造函数
var event = new Event('build');
// Listen for the event.
elem.addEventListener('build', function (e) { ... }, false);
// Dispatch the event.
elem.dispatchEvent(event);
相关连接见:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
fastclick中的真实做法
fastclick中有一个sendclick原型方法,目的是将模拟触发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
是给这个事件加的标签,方便跟踪。
第二行的方法参数太多,完全可以写成更加易读的形式:
clickEvent.initMouseEvent(this.determineEventType(targetElement), //type
true, //canBubble
true, //canCanceled
window, //view
1, //detail: 点击了几次
touch.screenX, //screenX
touch.screenY, //screenY
touch.clientX,
touch.clientY,
false, //ctrlKey,
false, //altKey
false, //shiftKey
false, //metaKey
0, //mouseEvent.button 0:鼠标左键 1:鼠标中键 2:鼠标右键
null //相关节点,在鼠标点击事件中设为null就好了,在mousein等事件中有用
);
相关连接:
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/initMouseEvent
网友评论