Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stopImmediatePropagation、Event.initEvent()、element.dispatchEvent(event)简单记录 #5

Open
pfan123 opened this issue May 9, 2017 · 0 comments

Comments

@pfan123
Copy link
Owner

pfan123 commented May 9, 2017

stopImmediatePropagation、Event.initEvent()、element.dispatchEvent(event)简单记录

创建和触发 events

Events 可以使用 Event构造函数 创建如下:

var event = new Event('build');

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

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

添加自定义数据 – CustomEvent()

CustomEvent 接口可以为 event 对象添加更多的数据。例如,event 可以创建如下:

var event = new CustomEvent('build', { 'detail': elem.dataset.time });

老式的方式: document.createEvent()、event.initEvent()已废弃

  var event = new MouseEvent('click', {
    'view': window,
    'bubbles': true,
    'cancelable': true
  });
  var cb = document.getElementById('checkbox');
  var cancelled = !cb.dispatchEvent(event);

stopImmediatePropagation

阻止当前事件的冒泡行为并且阻止当前事件所在元素上的所有相同类型事件的事件处理函数的继续执行.

fastclick解决点击延迟300ms的原理,首先,通常将事件绑定到 document.body(委托代理原理),其次,在代理过程中,通过stopImmediatePropagation移除目标节点绑定的事件, 最后是在touchend时,创建了一个鼠标事件,然后dispatchEvent事件(通过一系列的判断排除如长按、位置偏移,第二次点击等不触发click事件,反之出发sendClick()),使点击事件是在touchend时触发。

ps: dom节点多次绑定事件,当事件触发时会按事件绑定顺序依次执行。

//自定义事件,触发目标节点点击事件
FastClick.prototype.sendClick = function(targetElement, event) {
	var clickEvent, touch;

	// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
	if (document.activeElement && document.activeElement !== targetElement) {
		document.activeElement.blur();
	}

	touch = event.changedTouches[0];

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

移动端300ms延迟由来及解决方案
事件模型
fastclick
event.stopImmediatePropagation
【读fastclick源码有感】彻底解决tap“点透”,提升移动端点击响应速度
创建和触发 events
创建和触发 events
点击穿透

MouseEvent.initMouseEvent() -- 已废弃
Event.initEvent() -- 已废弃

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant