Home >Web Front-end >Front-end Q&A >Expand and close on click with javascript
As the needs of modern web design continue to grow, the demand for dynamic effects is also becoming more and more. One of the common needs is to click on a button or link to expand or close content. At this time, we can use JavaScript to implement this function.
JavaScript is a dynamic programming language that can manipulate HTML and CSS on web pages, as well as handle user interaction and dynamic effects. In the following demo, we will use JavaScript to create a button that expands and closes content.
First, we need to create an HTML page. In this page, we will add a DIV element that contains the content, and a button that expands and closes the content. The code is as follows:
<!DOCTYPE html> <html> <head> <title>JavaScript点击展开和关闭</title> <style> .content { display: none; /* 隐藏内容 */ } </style> </head> <body> <button onclick="toggle()">点击展开/关闭</button> <div class="content"> <p>我是一个可以展开和关闭的内容。</p> </div> <script src="script.js"></script> </body> </html>
In the above code, we create a button and a DIV element. The DIV element contains the content we want to expand or close. We also set the display of the DIV element to "none" so that the element will not be displayed initially.
Next, we need to add some JavaScript code to implement the expand and close functions. We place these codes in the script.js file.
let content = document.querySelector('.content'); function toggle() { if (content.style.display === 'none') { content.style.display = 'block'; } else { content.style.display = 'none'; } }
In the above code, we first use "document.querySelector" to get the DIV element containing the content and store it in the variable "content". Then we define a function called "toggle" that will be called when the button is clicked.
The "toggle" function uses an "if" statement to check whether the "display" attribute of the content DIV is "none". If so, the "toggle" function will set its "display" property to "block" so that it displays the content. Otherwise, the "toggle" function will set its "display" property to "none", hiding its content.
Now, we have completed the functionality of expanding and closing content. When the button is clicked, the content DIV will be shown or hidden, depending on its current display state. We can adjust the style and code according to our own needs to adapt to our own design needs.
JavaScript is a very powerful language that can add many dynamic and interactive features to web design. I hope this article was helpful and inspired you to try more JavaScript programming techniques.
The above is the detailed content of Expand and close on click with javascript. For more information, please follow other related articles on the PHP Chinese website!