Javascript切换而不使用类或ID

时间:2017-10-24 23:17:14

标签: javascript html css css-selectors semantics

我试图使用javascript显示和隐藏段落。但由于这是一个学校项目,因此有一些规则。我不能使用div类或id。这使我很难在Javascript中选择标签。它必须是语义的,因此不允许使用复选框hack和onclick属性。

这是codepen https://codepen.io/SummerD/pen/pWXWdy

这是我的HTML

<body>
<main>

  <section>

    <!-- Top part-->
    <span>
    <img src="https://www.w3schools.com/css/img_fjords.jpg"/>
    </span>

    <!-- Bottom part-->
    <summary>
      <button>show paragraph</button>
      <h2>Moe</h2>
      <h3>leeg</h3>
      <p>blah blah blah, this is the paragraph  <a href="#">read more</a> </p>
      <footer>6 Minutes</footer>
    </summary>

  </section>

</main>
</body>

这是我的css

section {
    width: 15em;
    margin: 2em;
    background-color: white;
    height: 23em;
}

  /*i'm trying to show/hide this p on click of the button*/

section summary p {
  display:none;
}

我已经尝试过这个:

var section = document.querySelector('section > summary > p');
var button = document.querySelector('section > summary > button');

var show = function () {
    section.classList.toggle('show')
}

button.addEventListener('click', show);

用这个css

section summary p {
    color: black;
    font-size: 0.8em;
    line-height: 1.8em;
  display:none;
}
section summary p.show {
  display:block;
}

但遗憾的是这不起作用。我不知道它是否因为拼写错误而无法正常工作,因为我老实说我不知道​​自己在做什么,我对javascript非常不好。

我希望你能帮助我!

1 个答案:

答案 0 :(得分:1)

具有讽刺意味的是,问题不在于您的按钮无法切换(实际上这样做很好),而是您无法在按钮上点击,因为{{1} }被<section>重叠。这是因为您在<main>部分有 z-index (问题代码中未显示),这意味着它位于-1之后,其默认<main>z-index(技术上为0,最终继承auto的默认0

只需删除它即可解决您的问题:

<html>

我创建了一个展示此here的新笔,并将其添加到以下代码段中:

section {
  /* z-index: 1 */
}
var section = document.querySelector('section > summary > p');
var button = document.querySelector('section > summary > button');

var show = function() {
  section.classList.toggle('show')
}

button.addEventListener('click', show);
* {
  box-sizing: border-box;
  font-family: Segoe UI, Myriad, Verdana, sans-serif;
}

body {
  background-color: grey;
}

main {
  display: flex;
  flex-flow: row wrap;
  justify-content: center;
}


/*=================
  =====the card====
  =================*/

section {
  width: 15em;
  margin: 2em;
  box-shadow: 0 0.2em 0.4em 0 rgba(0, 0, 0, 0.20);
  background-color: white;
  max-height: 23em;
}

/*top part*/

span {
  display: block;
  overflow: hidden;
  position: relative;
}

span img {
  width: 120%;
}

/*bottom part*/

section summary {
  bottom: 0;
  background: white;
  width: 100%;
  padding: 1em;
}

section summary h2 {
  margin: 0;
  padding-bottom: 0.5em;
  color: black;
  font-size: 1.5em;
  font-weight: 700;
}

section summary h3 {
  margin: 0;
  padding: 0 0 1em;
  color: darkred;
  font-size: 1em;
  font-weight: 400;
}

/*i'm trying to show/hide this p on click of the button*/

section summary p {
  color: black;
  font-size: 0.8em;
  line-height: 1.8em;
  display: none;
}

section summary p.show {
  display: block;
}

section summary footer {
  margin: 2em 0 0;
  color: black;
}

希望这有帮助! :)