gpt4 book ai didi

javascript - 单击子元素外的任意位置时如何隐藏父元素

转载 作者:行者123 更新时间:2023-11-30 10:00:48 25 4
gpt4 key购买 nike

我有这个代码

<style>

.Parent {width:500px;height:500px;background:#000}
.Parent .Child {width:250px;height:250px;background:#F00}

</style>

<div class="Parent">

<div class="child"></div>

</div>

<script>

$(document).ready(function() {

$('.Parent').click(function () {

$(this).hide()

});

/*
But if i click on <div class="Child"></div> ,
<div class="Parent"></div> won't get hidden .
*/

});

</script>

我希望我的代码隐藏'.parent',当我单击 .Parent 中的区域时,女巫不包含 .Child 元素,如果我单击的区域包含在“.child”区域中,则不会任何事物 。

那么你们有什么建议呢?

最佳答案

只需使用 event.stopPropagation(); 来阻止子事件传播到父事件。

所以脚本变成:

$('.Parent').click(function () {
$(this).hide();
});
$('.child').click(function (e) {
e.stopPropagation();
});

参见 fiddle :“http://jsfiddle.net/sftknxeo/1/

关于javascript - 单击子元素外的任意位置时如何隐藏父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31809663/

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