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

怎样触发一个scroll事件 #1

Open
shiye515 opened this issue Jul 4, 2016 · 0 comments
Open

怎样触发一个scroll事件 #1

shiye515 opened this issue Jul 4, 2016 · 0 comments

Comments

@shiye515
Copy link
Owner

shiye515 commented Jul 4, 2016

scroll事件的特点

[https://www.w3.org/TR/uievents/#event-types-list] 总结就是:

  • 首先,这个事件属于 UIEvent
  • 这个事件是异步的
  • 大多数情况下没有冒泡阶段(只有在document的触发时才会冒泡到window)
    alt text

创建事件对象

现代浏览器里的推荐做法

使用UIEvent()构造函数

var event = new UIEvent('scroll');

兼容过时浏览器

通过document.createEvent(type)创建,通过event.initUIEvent(type, canBubble, cancelable)初始化

var event = document.createEvent(‘UIEvent’);
event.initUIEvent(‘scroll’, false, true);

如果想在现代浏览器里使用新的构造函数,同时兼容过时浏览器,以下是推荐做法

var event;
try {
    event = new UIEvent('scroll');
} catch (e) {
    event = document.createEvent('UIEvents');
    event.initUIEvent('scroll', false, true);
}

原因是虽然有些过时浏览器有window.UIEvent这个对象,但是做构造函数用时会抛出异常

最后触发事件

element.dispatchEvent(event);

兼容大多数浏览器IE9+,Android2.3+,iOS4.1+

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