Last active
August 15, 2016 09:22
-
-
Save jinwei233/518e841f563fb7dc8899 to your computer and use it in GitHub Desktop.
跨浏览器的事件模拟
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// **跨浏览器的事件模拟** | |
// @keyword event-simulate,dispatchEvent,fireEvent,事件模拟 | |
// @author [email protected] | |
// 现有的功能库非常长,而且基本都抄自 yui 的代码 | |
// 比如: | |
// - https://github.com/totorojs/event-simulate | |
// - https://github.com/dxq613/event-simulate | |
// 有时我们只需要模拟简单的几个事件,这时候去 copy 一大段代码,或引入一个第三方库,显得不切实际 | |
// 有一个 jQuery 的插件很小 | |
// - https://github.com/eduardolundgren/jquery-simulate/blob/master/jquery.simulate.js | |
// 由于本人对 jQuery 插件无感,所以将其核心代码析出为简单的一个工具函数 `simulate` | |
// - 仅支持 MouseEvents、HTMLEvents | |
// - 可以简单修改,以支持更多的事件类型,参见 http://yuilibrary.com/yui/docs/api/files/event-simulate_js_event-simulate.js.html | |
// 使用方法: | |
// 1. simulate(window,"resize") | |
// 2. var a = document.getElementById("target") | |
// simulate(a,"click") | |
function simulate(el,type){ | |
// 这里写死了,可以添加一个参数进行配置 | |
var cancelable = true, bubbles=false; | |
var eventType; | |
// MouseEvents : see http://yuilibrary.com/yui/docs/api/files/event-simulate_js_event-simulate.js.html `mouseEvents` | |
if (['mouseover','mouseout','mousedown','mouseup','mousemove','contextmenu','click','dblclick'].indexOf(type) > -1) { | |
eventType = "MouseEvents"; | |
} | |
// HTMLEvents see http://yuilibrary.com/yui/docs/api/files/event-simulate_js_event-simulate.js.html `uiEvents` with HTML events supported | |
else if(["submit", "blur", "change", "focus", "resize", "scroll", "select"].indexOf(type) > -1){ | |
eventType = "HTMLEvents"; | |
} | |
if(document.createEvent){ | |
var e = document.createEvent(eventType); | |
e.initEvent(type,bubbles,cancelable) | |
el.dispatchEvent(e); | |
} | |
// IE 6 7 8 | |
else if(document.createEventObject){ | |
el.fireEvent('on'+type); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment