我想有我所有的段落文本崩溃时,页面加载。当我点击标题时,段落文本应该展开。我有多个标题(全部),所有包含在他们下面的段落。这是我正在做的课程的一部分,我们还没有学习JQuery,所以我需要在不使用JQuery的情况下工作。我将每个块放置在class="maincontent"中。参见下面的代码片段:
<div class="maincontent">
<h2>How HowziTO came to be? </h2>
<p>
This website was created by me, a South African who moved to Toronto in my mid 20's. Through the move, I felt unprepared, and at times, alone. Although there are many sites that offer advice to new immigrants,
I thought it would be useful to create a site that is specific to South Africans, given our unique heritage.
So, if you feel like I felt, hopefull this website will help you settle in a little easier.
If you have any suggestions for the site, please feel free to reach out to me using the <a href="About.html">the about page</a>.
</p>
</div>
我真的很感激任何帮助。谢谢你。
我在下面添加了我的网站的屏幕截图。从屏幕截图中,我想在"How HowziTO Came to be?"直到我点击标题,然后它展开。我希望其他两个标题也能起作用。
网站在您的代码中,您可以将'id'添加到您的p标签,并将id传递给h2标签上的onclick函数处理程序,如下所示-
<div class="maincontent">
<h2 onclick="expand('p1')">How HowziTO came to be?</h2>
<p id="p1">This website was created by me, a South African who moved to Toronto in my mid 20's. Through the move, I felt unprepared, and at times, alone. Although many sites offer advice to new immigrants,
</p>
</div>
添加display: none;
到p标签。
然后像这样添加JavaScript -
expand = id => {
let pTags = document.querySelectorAll('p');
pTags.forEach(ptag => {
ptag.style.display = 'none';
});
document.getElementById(id).style.display = 'block';
};
每次添加p标签时,都要向其添加元素id,并将id传递给h2标签中的展开函数。该函数自动关闭其他标签并展开所需的标签。
感谢大家的帮助。在搜索了提供的选项后,我决定使用onClick函数。下面是我的JS:
function toggleParagraph(event) {
var clickedHeading = event.target;
var paragraph = clickedHeading.nextElementSibling;
var table = paragraph.nextElementSibling;
if (paragraph.classList.contains("displayme")) {
if (paragraph.style.display === "none") {
paragraph.style.display = "block";
table.style.display = "block";
} else {
paragraph.style.display = "none";
table.style.display = "none";
}
}
}
我必须在我的HTML中添加以下内容:
<h2 onclick="toggleParagraph(event)">
和
<p class="displayme">
以及下面的CSS
.displayme {
display: none;
}
和
table {
display: none;
{
这允许我切换显示打开和关闭。