如何使用document.getElementsByClassName

时间:2016-08-20 06:56:55

标签: javascript html css

我有两个问题

  1. 请帮助我理解一些JavaScript来创建我从W3Schools获得的手风琴菜单
  2. CSS

        <style>
    button.accordion_f {
        background-color: #eee;
        color: #444;
        cursor: pointer;
        padding: 14px;
        width: 100%;
        border: none;
        text-align: left;
        outline: none;
        font-size: 15px;
        transition: 0.4s;
    }
    
    button.accordion_f.active, button.accordion_f:hover {
        background-color: #ddd;
        color: blue;
    }
    
    button.accordion_f:after {
        content: '\02795';
        font-size: 13px;
        color: #777;
        float: right;       
        margin-left: 5px;  
    }
    
    button.accordion_f.active:after {
        color: blue;
        content: "\2796";
    }
    
    div.panel {
        padding: 0 14px;
        background-color: white;
        max-height: 0;
        overflow: hidden;
        transition: 0.3s ease-in-out;
        opacity: 0;
    }
    
    div.panel.show {
        opacity: 1;
        max-height: 6000px;  
    }
    </style> 
    

    的JavaScript

    <script>
    var acc = document.getElementsByClassName("accordion_f");
    var i;
    
    for (i = 0; i < acc.length; i++) {
        acc[i].onclick = function(){
        this.classList.toggle("active");
        this.nextElementSibling.classList.toggle("show");       
        }
    }
    </script>
    

    使用示例

    <button class="accordion_f">3rd party compatibility</button>
    <div class="panel">
    <p>Offers an easy way to connect your Polar training device with 3<sup>rd</sup> party services.</p>
    </div>
    

    这可以正常使用

    如果我将它封装在另一个类中,例如在一个药丸菜单中,它将不会扩展菜单,css似乎工作,背景着色等,当我检查元素时我没有看到脚本,是父类影响document.getElementsByClassName有些怎样?

    <ul class="tabs">
    <button class="accordion_f">3rd party compatibility</button>
    <div class="panel">
    <p>Offers an easy way to connect your Polar training device with 3<sup>rd</sup> party services.</p>
    </div>
    </ul>
    
    1. 如何将我的脚本放入函数并使用onclick或onmouseover调用它?
    2. 我试过了:

      <button class="accordion_f" onmouseover="accordion_menu()">Activity</button>
      <div class="panel">
      <p>Tracks your daily activity at five intensity levels for 24 hours a day, seven days a week, and provides a complete picture of all of your activity. It counts your active time, daily burnt calories, steps, distance from steps and sleep.</p>
      </div>
      
      function accordion_menu(){
      var acc = document.getElementsByClassName("accordion_f");
      var i;
      
      for (i = 0; i < acc.length; i++) {
          acc[i].onclick.classList.toggle("active");        
          acc[i].onclick.nextElementSibling.classList.toggle("show");        
       }
      } 
      

      这只是用一个accordion_f类打开所有面板,而不仅仅是我想要的活动面板。

1 个答案:

答案 0 :(得分:-1)

它正在工作,I.E处于兼容模式,ie8对document.getElementsByClassName的支持不足