繁体   English   中英

如何选择兄弟元素的子元素?

[英]How can I select the child of a sibling element?

我的手风琴在打开和关闭的基础上不断填补我的div越来越大的空间。 我想在它周围包裹一个div并将其设置为扩展的手风琴的高度以防止这种行为。 麻烦是我的js依赖于选择this.nextSibling而且会破坏一切。

var acc = document.getElementsByClassName("review-button");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;

      if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + 'px';
    } 
  }
}

它必须在范围内使用“ this ”,因为有多个手风琴。 我最初的想法是做一些像......

this.nextElementSibling.children[0];

但那没用。

如何将当前内容包装在具有设定高度的div ,同时仍然保持手风琴功能?

<!--accordion 1-->     
<button class="review-button"  data-target="#demo{{ gameIndex }}">
     <span class="review-button-chevron fa fa-angle-down"></span>       
      Our Reviews
     </button>

<!-- Slide out -->
<div class="quote-machine-container">
    <div id="demo{{ gameIndex }}" class=" quote-machine"></div>
</div>

<!--accordion 2-->
 <button class="review-button"  data-target="#demo{{ gameIndex }}">
     <span class="review-button-chevron fa fa-angle-down"></span>       
      Our Reviews
     </button>

<!-- Slide out -->
<div class="quote-machine-container">
    <div id="demo{{ gameIndex }}" class=" quote-machine"></div>
</div>
  1. 将每个<header><div>放在它自己的<section>
  2. <main>包装了所有内容,并eventListener()添加了一个eventListener() 对它的任何点击都将被委托给被点击的标题( e.target 。)
  3. 事件处理程序( acc() )将:
    • 通过将e.target (点击节点)与e.currentTarget (此时捕获的节点)进行比较来确定它是什么。
    • 一旦建立, e.target将失去或获得.active类。
    • 为了消除nextElementSibling的限制属性,我们用一个简单的CSS规则集替换了该功能: .active + .x-panel ,它与nextElementSibling基本相同。

SNIPPET

 var main = document.getElementById("x-main"); main.addEventListener('click', acc, false); function acc(e) { if (e.target !== e.currentTarget) { var tgt = e.target; tgt.classList.toggle("active"); } } 
 .x-section { height: 100px; } .x-header { cursor: pointer; border: 3px outset grey; height: 30px; } .x-panel { border: 3px inset black; max-height: 0; opacity: 0; transition: opacity .2s ease-in; } .active + .x-panel { opacity: 1; max-height: 300px; overflow-y: hidden; transition: max-height 1s ease-in .1s, opacity 1s; } 
 <main id='x-main'> <section class='x-section'> <header class='x-header'>HEADER</header> <div class='x-panel'> CONTENT CONTENT CONTENT CONTENT CONTENT CONTENT CONTENT </div> </section> <section class='x-section'> <header class='x-header'>HEADER</header> <div class='x-panel'> CONTENT CONTENT CONTENT CONTENT CONTENT CONTENT </div> </section> <section class='x-section'> <header class='x-header'>HEADER</header> <div class='x-panel'> CONTENT CONTENT CONTENT CONTENT CONTENT CONTENT CONTENT CONTENT </div> </section> </main> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM