最近在 安卓自带浏览器 上发现 new CustomEvent('input') 不兼容
解决办法
(function () {
if(!!window.CustomEvent) return;
function CustomEvent ( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent( 'CustomEvent' );
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
return evt;
}; CustomEvent.prototype = window.Event.prototype; window.CustomEvent = CustomEvent;
})();
http://*.com/questions/23920708/get-short-javascript-customevent-polyfill-to-compile-in-typescript
其他的
function triggerEvent(element,eventType){
var e;
if(element.dispatchEvent){//正常情况
e = new Event(eventType);
element.dispatchEvent(e);
}else if(element.fireEvent){//IE
e = document.createEventObject();
e.button = 1;
element.fireEvent('on'+eventType,e);
}else if(element['on'+eventType]){
element['on'+eventType].call();
}
}
try {
evt = new window.CustomEvent(events[i], {
detail: eventData,
bubbles: true,
cancelable: true,
});
} catch (e) {
evt = document.createEvent('Event');
evt.initEvent(events[i], true, true);
evt.detail = eventData;
}
//create custom event
if (typeof document.CustomEvent === 'function') {
this.event = new document.CustomEvent('shake', {
bubbles: true,
cancelable: true
});
} else if (typeof document.createEvent === 'function') {
this.event = document.createEvent('Event');
this.event.initEvent('shake', true, true);
} else {
return false;
}
window.dispatchEvent(this.event);
//创建事件, Event是无法传递参数的
var event = new Event('suface');
//创建事件, CustomEvent是可以传递参数的
var event = new CustomEvent('suface', { detail: elem.dataset.time }); // 监听事件Listen for the event.
elem.addEventListener('suface', function (e) { //... }, false); // 分发/触发事件Dispatch the event.
elem.dispatchEvent(event);
HTMLElement.prototype.trigger = function(type, data) {
var event = document.createEvent('HTMLEvents');
event.initEvent(type, true, true);
event.data = data || {};
event.eventName = type;
event.target = this;
this.dispatchEvent(event);
return this;
}