最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - once:true with addEventListener doesn't work on IE11 or Edge - Stack Overflow

programmeradmin4浏览0评论

I'm trying to fire an event listener callback just once. addEventListener conveniently has a flag that I can pass into it:

once: A Boolean indicating that the listener should be invoked at most once after being added. If it is true, the listener would be removed automatically when it is invoked.

This works fantastic in every browser except IE11 and Edge. I know that I can manually remove the event listener after it fires, but this flag should work... Am I doing something wrong, or is this an acknowledged issue with IE or what?

Should you prefer JSFiddle, otherwise:

var div = document.getElementById('transition');
var result = document.getElementById('result');

window.grow = function(){
  var width = div.offsetWidth + 50;
  div.style.width = width + 'px';
}

var count = 0;
div.addEventListener('transitionend', function(){
  result.innerHTML = "transitionend has fired " + ++count + " times";
}, { once: true });
#transition{
  background-color: yellow;
  transition: width 2s;
  width: 100px;
}
<div id="transition">
  Content
</div>
<button onclick="grow()">
  Grow the div
</button>
<div id="result">

</div>

I'm trying to fire an event listener callback just once. addEventListener conveniently has a flag that I can pass into it:

once: A Boolean indicating that the listener should be invoked at most once after being added. If it is true, the listener would be removed automatically when it is invoked.

This works fantastic in every browser except IE11 and Edge. I know that I can manually remove the event listener after it fires, but this flag should work... Am I doing something wrong, or is this an acknowledged issue with IE or what?

Should you prefer JSFiddle, otherwise:

var div = document.getElementById('transition');
var result = document.getElementById('result');

window.grow = function(){
  var width = div.offsetWidth + 50;
  div.style.width = width + 'px';
}

var count = 0;
div.addEventListener('transitionend', function(){
  result.innerHTML = "transitionend has fired " + ++count + " times";
}, { once: true });
#transition{
  background-color: yellow;
  transition: width 2s;
  width: 100px;
}
<div id="transition">
  Content
</div>
<button onclick="grow()">
  Grow the div
</button>
<div id="result">

</div>

Share Improve this question edited Jul 14, 2021 at 17:38 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 30, 2016 at 21:38 adamdportadamdport 12.7k14 gold badges73 silver badges92 bronze badges 1
  • 4 it's a new trick, which old dogs can't do. – dandavis Commented Dec 30, 2016 at 21:49
Add a ment  | 

1 Answer 1

Reset to default 5

Check the browser patibility section of the docs: no IE/edge support. caniuse is also helpful.

发布评论

评论列表(0)

  1. 暂无评论