【发布时间】:2018-04-05 21:28:06
【问题描述】:
我正在尝试使用 javascript 显示和隐藏段落。但由于这是一个学校项目,所以有一些规则。我不能使用 div 类或 id。这让我很难在 Javascript 中选择标签。它必须是语义的,因此不允许使用复选框 hack 和 onclick 属性。
这里是密码笔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。
希望你能帮帮我!
【问题讨论】:
-
您浏览器的开发者工具中是否报告了任何错误?
-
hole web 是围绕 div、class 和 id 构建的。不使用它们只是愚蠢的...无论如何,如果您想尝试隐藏/显示段落并使其更具语义而不使用任何javascript或复选框黑客,请尝试使用
<details> -
@endless 根据我学校的 div 是 html4,我们必须使用 html5 结构元素来代替。我们不允许在这个特定项目中使用 class 或 id 来练习 css 选择器。
-
“使用 css 选择器练习”Okey 这是一个很好的正当理由 :)
标签: javascript html css css-selectors semantics