繁体   English   中英

如何使用document.getElementsByClassName

[英]How to use document.getElementsByClassName

我有两个问题

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

的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似乎可以正常工作,背景阴影等,当我检查元素时看不到脚本,是影响文档的父类。 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调用它?

我试过了:

<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");        
 }
} 

这样就打开了所有带有手风琴类的面板,而不仅仅是我想要的活动面板。

它正在运行,IE处于兼容模式,ie8对document.getElementsByClassName的支持不佳

暂无
暂无

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

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