如何显示和隐藏<div>?

时间:2019-08-01 00:44:28

标签: javascript jquery dom toggle

我的任务是使用DOM显示和隐藏<div>h2有多个,但是只有一个具有ID,并且不允许添加ID或类。如何只显示和隐藏一个div。我需要显示的带有div的h2的ID为info

这是我的代码的片段:

body {
  font-family: Verdana, Arial, Helvetica, sans-serif;
  font-size: 100%;
  margin: 20px;
  padding: 10px;
}

section {
  margin-bottom: 50px;
}

footer p {
  border-top: 1px solid #000;
  padding: 10px;
}

#info div:first-of-type {
  display: none;
}

#info div.more {
  display: block;
}

#info h2 {
  cursor: pointer;
}
<body>
  <section>
    <figure>
      <img s src="https://media.swansonvitamins.com/images/items/250/JR187.png" alt="Photo of Curcumin 95">
    </figure>
    <ul>
      <li>Curcumin 95 protects against oxidative damage</li>
      <li>Delivers 95% curcuminoids</li>

    </ul>
  </section>
  <section id="info">
    <h2>Show More...</h2>
    <div>
      <p>Other Ingredients: Cellulose, magnesium stearate (vegetable source) and silicon dioxide. Capsule consists of hydroxypropylmethylcellulose.
      </p>

      <p>Usage: Take 1 capsule per day with food or as directed by your qualified healthcare professional</p>

      <p>Note: ...</p>
    </div>

    <h2>Our Guarantee</h2>
    <div>
      <p>Our lab evaluates...</p>
    </div>

2 个答案:

答案 0 :(得分:0)

我认为...您必须在h2标签中创建onclick事件...然后包含脚本代码 $(this).css('display','block')

答案 1 :(得分:0)

var h2List = document.querySelectorAll('#info h2')
h2List.forEach(h2 => { 
  h2.addEventListener('click', () => h2.nextSibling.classList.toggle('more'))
})

我想这就是你想要的