为了了解事件冒泡是如何工作的,我创建了许多 div 控件,一个到另一个等等,最后将点击事件附加到所有 div,这使得 div 在被单击时闪烁。我希望一个 div 会闪烁,然后另一个 div 会像这样冒泡到父级,但所有 div 同时闪烁。
为什么一个事件处理程序在调用另一个事件处理程序之前没有完成?动画功能是否正在做某事?因为它通常不会发生,所以我一直注意到只有在完成一个事件处理程序后才会调用另一个事件处理程序。
这是我的js:
$("div").on("click", function (e) {
$(this).animate({ backgroundColor: "red" }, 400, "swing", function () {
$(this).animate({ backgroundColor: "white" }, 400, "swing")
})
})
这是HTML:
<div><div><div><div><div><div><div>
</div></div></div></div></div></div></div>
最佳答案
来自 Jquery http://api.jquery.com/animate/
Animation Properties and Values All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color plugin is used). Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable.
该页面中提到了一个插件,可以使背景颜色动画化。同样在您的代码中,您可能想要或可能不想合并:
e.stopPropogation();
这将阻止 div 事件冒泡。
你可以:
$("div").on("click", function (e) {
$(this).css({backgroundColor: "red", opacity: 0})
$(this).animate({ opacity: 1 }, 400, "swing", function () {
$(this).css({backgroundColor: "white", opacity: 0})
$(this).animate({ opacity: 1 }, 400, "swing")
})
})
但它会有不同的效果,div 会消失并重新出现红色,然后消失并重新出现白色。
如果您只是想暂停传播然后在动画结束时重新开始,您可以重新触发父元素上的事件;
$("div.animate").on("click", function (e) {
e.stopPropagation();
$(this).animate({ backgroundColor: "red" }, 400, "swing", function () {
$(this).animate({ backgroundColor: "white" }, 400, "swing", function(){
$(e.target.parentElement).trigger(e.type);
})
})
})
要仅使某些 div 具有动画效果,只需向它们添加一个“动画”类,然后将处理程序附加到仅具有动画效果的 div,任何其他 div 将自动传播点击,而您的动画类 div 会停止传播、动画和当完成向上传递 DOM 树时。
关于javascript - 事件处理程序继续调用早于动画函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51584400/