使用window.onclick隐藏div的问题

问题描述 投票:0回答:1

当我在父级外部单击时,我试图将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>

现在切换diplay:block / none的功能无效,但是在父级外部单击时应该隐藏该功能的功能不起作用。

javascript html function var
1个回答
0
投票

您应该在函数之外编写窗口单击事件的代码。如果要在单击窗口时隐藏所有子元素,请尝试以下方法:

function myfunction(elmnt, e) {
  e.stopPropagation();
  var child = elmnt.children[0];
  if (child.style.display === "none") {
    child.style.display = "block";
  } 
  else {
    child.style.display = "none";
  }

}

window.onclick = function() {
  var childList = document.querySelectorAll('.child');
  [...childList].forEach(function(child){
    child.style.display = "none";
  });
}
<div class="parent" style="margin:10px; cursor:pointer; background-color:lime; width:150px; height:50px;" onclick="myfunction(this, event)">
    <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, event)">
    <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, event)">
    <div class="child" style="100px; height:20px; color: black; background-color:red; display:none;">Child3</div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.