针对Vanilla JS中父元素的同级

时间:2019-06-01 19:04:22

标签: javascript

我正在尝试定位父元素的同级对象,但是没有触发。 根据先前的经验并查看其他示例,我应该能够添加'parentElement'使其在dom树中向上移动,就像下面的w3示例:https://www.w3schools.com/jsref/prop_node_parentelement.asp

我的问题的工作示例:https://www.w3schools.com/code/tryit.asp?filename=G4M9OTXD3D42

我之前问过基本相同的问题-已成功回答(不同的代码/问题)。但是,它仍然是症结所在。

var acc = document.getElementsByClassName("accordion-sibling-child");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.parentElement.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    } 
  });
}
.accordion-sibling-child {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
  transition: 0.4s;  
  display: block;
  font-family: sans-serif;
}

.active {
  background-color: #ccc;
}

.panel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
}
<div>
  <a class="accordion-sibling-child">Accordion thats a child of a sibling to the expansion panel</a>
<div/>
<div class="panel">
  <p>Lorem ipsum dolor... </p>
</div>

0 个答案:

没有答案