javascript - e.stopPropagation 不工作

标签 javascript css events transition stoppropagation

我向元素添加了一个 transtionend 回调事件。这个元素有一个也有过渡的子元素。

问题是,当 child 的转换结束时,它的父 transitionend 事件被调用。

我尝试将 e.stopPropagation() 添加到 transitionend 事件中,但没有帮助。它似乎没有做任何事情。当 child 完成其过渡时,如何防止发生 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>

最佳答案

我从问题和评论中了解到,您不希望 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 捕获......所以最好的方法是检查事件目标,然后做出决定。

希望对您有所帮助!

关于javascript - e.stopPropagation 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36274519/

相关文章:

javascript - jquery 触发自定义全局事件

javascript - 将 ng-data 传递到作用域

javascript - ExtenderControlProperty 双向绑定(bind)?

css - SASS 在多行上缩进语法?

javascript - 第二次和第三次点击时的事件

java - 鼠标拖动画线组滞后的原因

javascript - TinyMCE以编程方式隐藏工具栏溢出

javascript - 按坐标绘制大厅平面图

javascript - 为什么 JavaScript 中的下划线功能不起作用?

html - HTML 按钮上的奇怪格式