gpt4 book ai didi

javascript - e.stopPropagation 不工作

转载 作者:行者123 更新时间:2023-11-29 15:29:22 25 4
gpt4 key购买 nike

我向元素添加了一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com