Home > Web Front-end > JS Tutorial > body text

How to use JavaScript to display hidden text when clicking a button?

WBOY
Release: 2023-10-21 11:49:41
Original
1315 people have browsed it

如何使用 JavaScript 实现点击按钮显示隐藏文本的功能?

How to use JavaScript to implement the function of clicking a button to display hidden text?

In front-end development, we often encounter the need to click a button to display or hide some text content. This functionality can be easily implemented using JavaScript. This article will teach you how to use JavaScript to switch the display and hidden state of text, and provide specific code examples.

First, add a button in HTML and switch to display hidden text content:

<button id="toggleButton">点击切换显示/隐藏</button>
<div id="textContent" style="display: none;">
    这是切换显示/隐藏的文本内容。
</div>
Copy after login

In the above code, we added a button and gave it a unique id toggleButton. In the <div> element, we set the style of display: none; to initially hide the text content.

Next, we use JavaScript to implement the function of switching display and hiding. Add the following code block in the HTML file:

<script>
    var toggleButton = document.getElementById("toggleButton");
    var textContent = document.getElementById("textContent");

    toggleButton.addEventListener("click", function() {
        if (textContent.style.display === "none") {
            textContent.style.display = "block";
        } else {
            textContent.style.display = "none";
        }
    });
</script>
Copy after login

In the above code, we first get the element with the unique id of the button and text content. Then, we use addEventListener to add a click event listener. When the button is clicked, the corresponding function is executed.

The function logic in the event listener is very simple: check the display attribute of the text content. If "none", set it to "block" to show the text content; if "block", set it to "none" to hide the text content.

Now, you can run the code in the browser and click the button to toggle showing and hiding the text content.

The above are the detailed steps and code examples of using JavaScript to implement the function of clicking a button to display hidden text. With simple JavaScript code, you can easily implement this feature to add interactivity and user experience to your web pages.

The above is the detailed content of How to use JavaScript to display hidden text when clicking a button?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template