为什么我的手风琴没有打开

时间:2017-01-07 21:07:14

标签: javascript jquery css css3

从这里的例子http://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_accordion开始,我希望我的手风琴能够开启,所以我在课堂上添加了w3-show风格,但为什么它不起作用?

<!DOCTYPE html>
<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<body>

<div class="w3-container">
<h2>Accordions</h2>
<p>An accordion is used to show (and hide) content that is broken into sections:</p>

<div class="w3-accordion w3-light-grey">
    <button onclick="myFunction('Demo1')" class="w3-btn-block w3-left-align w3-show">Open Section 1</button>
    <div id="Demo1" class="w3-accordion-content w3-container">
    <h4>Section 1</h4>
    <p>Some text..</p>
    </div> 
    <button onclick="myFunction('Demo2')" class="w3-btn-block w3-left-align w3-show">Open Section 2</button>
    <div id="Demo2" class="w3-accordion-content w3-container">
    <h4>Section 2</h4>
    <p>Some other text..</p>
    </div>
</div>
</div>

<script>
function myFunction(id) {
    var x = document.getElementById(id);
    if (x.className.indexOf("w3-show") == -1) {
        x.className += " w3-show";
    } else { 
        x.className = x.className.replace(" w3-show", "");
    }
}
</script>

</body>
</html>

2 个答案:

答案 0 :(得分:1)

你的w3-show类必须是像这样的容器Demo2和Demo1:

    <button onclick="myFunction('Demo2')" class="w3-btn-block w3-left-align">Open Section 2</button>
<div id="Demo2" class="w3-accordion-content w3-container w3-show">

在浏览器中使用F12检查您的html代码时,您可以看到w3-show类在您的demo-div上切换

答案 1 :(得分:1)

默认情况下,您可以在类w3-show的元素上添加w3-accordion-content类。试试这个:

function myFunction(id) {
  var x = document.getElementById(id);
  if (x.className.indexOf("w3-show") == -1) {
    x.className += " w3-show";
  } else {
    x.className = x.className.replace(" w3-show", "");
  }
}
<link href="http://www.w3schools.com/lib/w3.css" rel="stylesheet"/>
<div class="w3-container">
  <h2>Accordions</h2>
  <p>An accordion is used to show (and hide) content that is broken into sections:</p>

  <div class="w3-accordion w3-light-grey">
    <button onclick="myFunction('Demo1')" class="w3-btn-block w3-left-align">Open Section 1</button>
    <div id="Demo1" class="w3-accordion-content w3-container w3-show">
      <h4>Section 1</h4>
      <p>Some text..</p>
    </div>
    <button onclick="myFunction('Demo2')" class="w3-btn-block w3-left-align ">Open Section 2</button>
    <div id="Demo2" class="w3-accordion-content w3-container w3-show">
      <h4>Section 2</h4>
      <p>Some other text..</p>
    </div>
  </div>
</div>