簡體   English   中英

IE 不支持 CustomEvent() 構造函數

[英]CustomEvent() constructor is not supportive in IE

IE 不支持CustomEvent()構造函數。 是否有可能使其至少與 IE11 兼容? 它適用於 Chrome 和 Firefox 等其他瀏覽器。

前任:-

var SpecialEvent = new CustomEvent(
  "SpecialMessage",
  {
   detail:
   {
     message: "Hello There",
     time: new Date()
   },
   bubbles: true,
   cancelable: true
  });

MDN 為 IE >= 9 提供了一個 polyfill。見下文。
https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent

(function () {

  if ( typeof window.CustomEvent === "function" ) return false;

  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;
})();

這應該適用於 IE9+

 var SpecialEvent = document.createEvent("CustomEvent"); SpecialEvent.initCustomEvent('SpecialMessage', false, false, { detail: { message: "Hello There", time: new Date() }, bubbles: true, cancelable: true });

從這里獲取.. 為什么我的參數沒有傳遞到已調度的事件?

使用更少的時間和精力,通過切換到 jQuery 事件而不是使用一些特殊的原型醬來讓 IE 工作,從而為自己節省未來的困難。 jQuery 事件有更好的實現並且與 IE 兼容。

[除非你跨幀觸發事件,那么你需要原型並使用傳統的window.dispatchEvent(evt) ]

舊方式:

var SpecialEvent = new CustomEvent(
  "SpecialMessage",
  {
   detail:
   {
     message: "Hello There",
     time: new Date()
   },
   bubbles: true,
   cancelable: true
  });

新方法:

$(window).trigger("SpecialMessage", ["Hello There", new Date()]);

並捕捉該事件:

$(window).on("SpecialMessage",function(e, arg1, arg2){
    console.log(arg1);   // Hello There
    console.log(arg2);   // 2018-04-18...
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM