【发布时间】:2020-01-28 09:11:34
【问题描述】:
当我在父级之外单击时,我试图将一个 div 隐藏在其他 div 中。问题是我不想使用 ID,因为我希望这是一个全局函数(对不起我的英语)。
现在我在父元素onclick="myfunction(this)" 中选择子元素,然后(在脚本中)使用element.children[0] 做一个变量来显示子元素。
问题是当我试图隐藏孩子在父母之外点击时,因为变量取决于myfunction。
function myfunction(elmnt) {
var child = elmnt.children[0];
if (child.style.display === "none") {
child.style.display = "block";}
else {
child.style.display = "none";};
// window.onclick = function(event) {child.style.display = "none";}
}
<div class="parent" style="margin:10px; cursor:pointer; background-color:lime; width:150px; height:50px;" onclick="myfunction(this)">
<div class="child" style="100px; height:20px; color: black; background-color:red; display:none;">Child1</div>
</div>
<div class="parent" style="margin:10px; cursor:pointer; background-color:lime; width:150px; height:50px;" onclick="myfunction(this)">
<div class="child" style="100px; height:20px; color: black; background-color:red; display:none;">Child2</div>
</div>
<div class="parent" style="margin:10px; cursor:pointer; background-color:lime; width:150px; height:50px;" onclick="myfunction(this)">
<div class="child" style="100px; height:20px; color: black; background-color:red; display:none;">Child3</div>
</div>
现在切换 display:block/none 子项的功能可以使用,但是在父项外部单击时应该隐藏子项的功能不起作用。
【问题讨论】:
标签: javascript html function var