Проблемы скрыть div с помощью window.onclick - PullRequest
0 голосов
/ 28 сентября 2019

Я пытаюсь скрыть 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>

Теперь функция, которая переключает отображение: блок / нет, дочерний элемент работает, но функция, которая должна скрывать дочерний элемент при щелчке вне родительского элемента, не работает.

1 Ответ

0 голосов
/ 28 сентября 2019

Манул дал правильный ответ, но установленное событие в окне неверно.

Необходимо обработать необходимость выполнения обработчика.Чтобы избежать ошибок и ненужной загрузки в интерфейсе.

var globalEventSet = false;

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

}

function setEventOnWindow(){

  let callback = function(ev) {
    var childList = document.querySelectorAll('.child');
    
    if(childList != null) {
       [...childList].forEach(function(child){
            child.style.display = "none";
       })
    } 
    
    console.log("i'm work only once (;");
    
    window.removeEventListener('click', callback );
    
    globalEventSet = false;
  }

  window.addEventListener('click', callback );
}
<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>
...