Javascript:显示内容未从“阻止”更改为“无”

时间:2018-06-27 17:41:50

标签: javascript

单击elements(红色方框)后,将调用func函数,并获取第一个子节点,然后该节点更改为“ block”。现在,我尝试通过获取none的父节点,单击background_dim(深色背景),然后将其设置回background_dim,然后遍历子节点并将其显示设置为none。但是显然这是行不通的。仅当我将其位置设置为relative时,该方法才有效,但是我还必须更改其他功能。

function func(element) {
  var _first_child = element.children[0];
  for (var i = 0; i < _first_child.children.length; ++i)
    _first_child.children[i].style.display = "block";
}

function func_t(element) {
  var _parent = element.parentNode;
  for (var i = 0; i < _parent.children.length; ++i)
    _parent.children[i].style.display = "none";
}
.elements {
  width: 40px;
  height: 40px;
  background-color: red;
}

.background {
  display: none;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100%;
  width: 100%;
  background-color: rgb(0, 0, 0, 0.7);
}

.display-container
{
  display: none;
  position: fixed;
  top: 50%;
  bottom: 30%;
  left: 50%;
  right: 0;
  height: 100%;
  width: 100%;
  background-color: green;
  
}
<html>

  <body>
    <ul>
      <li class="elements" onclick="func(this);">
        <div class="_display_job_dim_">
          <div class="background" onclick="func_t(this);"></div>
          <div class="display-container"></div>
        </div>
      </li>
    </ul>
  </body>
 
</html>

https://jsfiddle.net/waxebm81/285/

1 个答案:

答案 0 :(得分:0)

您的问题是,如果在background_dim上发生点击,则默认情况下它将在DOM中传播,因此,在调用func_t之后,事件将传播到.elements和{{ 1}}被调用,它将再次显示元素。

因此,您必须停止事件的传播:

func(this)
document.querySelector('.elements').addEventListener('click', func, false)
document.querySelector('.background_dim').addEventListener('click', func_t, false)


function func(evt) {
  evt.stopPropagation();
  var element = evt.target;
  var _first_child = element.children[0];
  for (var i = 0; i < _first_child.children.length; ++i) {
    _first_child.children[i].style.display = "block";
  }

}

function func_t(evt) {
  evt.stopPropagation();
  var element = evt.target;
  var _parent = element.parentNode;
  for (var i = 0; i < _parent.children.length; ++i) {
    _parent.children[i].style.display = "none";
  }

  return false;
}
.elements {
  width: 40px;
  height: 40px;
  background-color: red;
}

.background_dim {
  display: none;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100%;
  width: 100%;
  background-color: rgb(0, 0, 0, 0.7);
}

.display-container {
  display: none;
  position: fixed;
  top: 50%;
  bottom: 30%;
  left: 50%;
  right: 0;
  height: 100%;
  width: 100%;
  background-color: green;
}