e.stopPropagation无效

时间:2016-03-29 02:50:52

标签: javascript css events transition stoppropagation

我在元素中添加了transtionend回调事件。该元素还有一个具有转换的子元素。

问题在于,当孩子的转换结束时,会调用其“父transitionend事件。

我尝试将e.stopPropagation()添加到transitionend事件中,但它没有帮助。它似乎没有做任何事情。如何在孩子完成转换时阻止transitionend事件发生?

JSFiddle

var outer = document.getElementById('outer'),
  content = document.getElementById('content'),
  outerButton = document.getElementById('outerButton'),
  contentButton = document.getElementById('contentButton');

outerButton.addEventListener('click', function() {
  outer.style.width = (outer.style.width === '300px') ? '500px' : '300px';
});

contentButton.addEventListener('click', function() {
  content.style.width = (content.style.width === '150px') ? '250px' : '150px';
});

if ('transition' in document.documentElement.style) {
  outer.addEventListener('transitionend', function(e) {
    alert('transitionend');
    console.log('before');
    e.stopPropagation();
    console.log('after');
  });
}
#outer {
  width: 500px;
  background-color: orange;
  transition: width 0.7s ease-in-out;
}
#content {
  background-image: url("http://i.imgur.com/nri7bYd.jpg");
  height: 200px;
  width: 250px;
  transition: width 0.7s ease-in-out;
}
<div id="outer">
  <div id="content">This is some content</div>
</div>

<button id="outerButton">Change Width of Outer (orange) Element</button>
<br />
<br />
<button id="contentButton">Change Width of Content (image) Element</button>

2 个答案:

答案 0 :(得分:1)

我从问题和评论中理解的是,您不希望在子元素上发生transitionend事件。

从上面的代码中,由于您已将转换结束事件应用于父级(在本例中为外部),因此这也将捕获所有子事件。

处理此问题的最佳方法是在方法中添加一个检查。

if ('transition' in document.documentElement.style) {
  outer.addEventListener('transitionend', function(e) {
if(e.target == content) { return;}
    console.log('before');
    e.stopPropagation();
    console.log('after');
  });
}

这里e.stopPropagation();停止事件进一步传播,例如,如果你有grandParent div,那么事件将不会去那里,但在这种情况下,因为事件来自child,它被outer.addEventListener捕获...所以最好的方法是检查事件目标,然后做出决定。

希望它有所帮助!!

答案 1 :(得分:0)

据我所知,你在寻找这个:

Here is the JSFiddle demo

init=()=>{
//VARIABLE DECLARATION  
var outer = document.getElementById('outer'),
    content = document.getElementById('content'),
    outerButton = document.getElementById('outerButton'),
    contentButton = document.getElementById('contentButton');
//SET EVENT LISTENERS
outerButton.addEventListener('click',()=>outer.style.width = (outer.style.width === '300px') ? '500px' : '300px');
outer.addEventListener('transitionend',()=>console.log('PARENT (OUTER) CSS TRANSISITION ENDING...'));
content.addEventListener('transitionend',(e)=>e.stopPropagation());
contentButton.addEventListener('click',()=>content.style.width = (content.style.width === '150px') ? '250px' : '150px');
}
//INIT
document.addEventListener('DOMContentLoaded', init);
相关问题