如何使用 JavaScript 创建网站的常见问题解答 (FAQ) 部分?
在本文中,我们将使用 JavaScript 创建一个 FAQ(常见问题解答)手风琴。手风琴用于显示问题,点击后展开以显示答案。我们可以在每个网站上看到 FAQ 部分,其中涵盖了所有主要问题。今天我们将学习如何制作这些 FAQ 部分。
创建手风琴的步骤
步骤一 - 首先,我们将创建一个嵌套的 HTML div 标签,用于容纳所有问题和答案。这些 div 标签将取决于要显示的 QnA 的数量。
步骤二 - 我们将使用 CSS 提供更好的用户界面。常用的属性包括字体大小、边距、填充、颜色等。
步骤三 - 我们还需要添加一个 JavaScript 函数,该函数将在点击时呈现答案并显示它们。答案将通过点击问题来显示。
示例
在下面的示例中,我们添加了一些问题并为其提供了答案。这些问题通常显示,但只有在用户点击后才会显示答案。我们已将事件监听器放置到按钮上,并且当用户点击链接时,它将打开 div 并显示答案。
#文件名:index.html
<!DOCTYPE html> <html lang="en"> <head> <title>FAQ</title> <style> .layout{ width: 600px; margin: auto; } .accordion{ padding: 10px; margin-top: 10px; margin-bottom: 10px; /*background: r;*/ border-radius: 10px; border: 2px solid black; } .accordion__question p{ margin: 5px; padding: 0; font-family: consolas; font-size: 20px; } .accordion__answer p{ margin: 5px; padding: 10px; font-size: large; font-family: Verdana, Geneva, Tahoma, sans-serif; color: white; background: grey; border-radius: 10px; } .accordion:hover{ cursor: pointer; } .accordion__answer { display: none; } .accordion.active .accordion__answer { display: block; } </style> </head> <body> <h2 style="color:green; text-align:center"> Welcome To Tutorials Point </h2> <div class="layout"> <div class="accordion"> <div class="accordion__question"> <p>Who started tutorialspoint.com? When? Who owns it?</p> </div> <div class="accordion__answer"> <p>Tutorialspoint.com is a dedicated website to provide quality online education in the domains of Computer Science, Information Technology, Programming Languages, and other Engineering as well as Management subjects. This website was launched by an AMU alumni, Mr. Mohtashim, with a single tutorial on HTML in year 2006.</p> </div> </div> <div class="accordion"> <div class="accordion__question"> <p>Where is Tutorials Point (I) Pvt. Ltd. located?</p> </div> <div class="accordion__answer"> <p>We are located in Hyderabad, the beautiful city of Nizam. Our postal address is −Tutorials Point (I) Pvt. Ltd., 4th Floor, INCOR 9 Building, Plot No - 283/A, Kavuri Hills, Madhapur, Hyderabad, Telangana, INDIA-500081 INDIA</p> </div> </div> <div class="accordion"> <div class="accordion__question"> <p>What is current traffic on tutorialspoint.com?</p> </div> <div class="accordion__answer"> <p>At present, tutorialspoint.com is read by 13 million students and professionals around the world who access almost 35 million pages every month. The number of our users is multiplying every year.</p> </div> </div> </div> <script> let answers = document.querySelectorAll(".accordion"); answers.forEach((event) => { event.addEventListener('click', () => { if (event.classList.contains("active")) { event.classList.remove("active"); } else { event.classList.add("active"); } }) }) </script> </body> </html>
输出
广告