Home > Article > Web Front-end > How to control body display and hiding with javascript
In front-end development, javascript is an indispensable part, and controlling the display and hiding of page elements is a very common requirement. To control the display and hiding of the entire page, you need to control the display and hiding of the body element. This article will introduce how to use javascript to control the display and hiding of the body element.
First, we need to get the body element. In javascript, it can be obtained through document.body. For example:
var body = document.body;
Next, we need to control the display and hiding of the body element. This can be achieved by modifying the display attribute in the style attribute of the body element. If the display attribute is set to "none", the body element will be hidden; if the display attribute is set to "block", the body element will be displayed. For example:
// 隐藏body元素 body.style.display = "none"; // 显示body元素 body.style.display = "block";
However, in actual development, we rarely directly operate the style attribute of the element. Instead, style sheets are used to control the style of page elements. Therefore, controlling the display and hiding of the body element can also be achieved by operating the style sheet.
In the head tag of the HTML page, you can add the following style sheet:
<style> body.hidden { display: none; } </style>
This style sheet defines a class named "hidden", in which the display of the body element is The property is set to "none" to hide the body element.
Now, we can control the body element to add or delete the "hidden" class through javascript. For example:
// 隐藏body元素 body.classList.add("hidden"); // 显示body元素 body.classList.remove("hidden");
Finally, let’s look at a complete application example. Suppose we have a page with a button on it. Clicking the button can control the display and hiding of the page. We can implement it by following the following steps:
<head> <style> body.hidden { display: none; } </style> </head>
<body> <button onclick="toggle()">显示/隐藏</button> <!-- 页面内容 --> </body>
function toggle() { var body = document.body; body.classList.toggle("hidden"); }
Now, when the user clicks the button, the toggle function will be triggered, which controls the display and hiding of the body element by operating the style sheet.
Summary
Through the above examples, we can see that in JavaScript, controlling the display and hiding of the body element can be achieved by directly operating the style attribute of the element, or by operating the style sheet. . For needs that require more flexible control of page styles, it is recommended to use style sheets to control the styles of elements.
The above is the detailed content of How to control body display and hiding with javascript. For more information, please follow other related articles on the PHP Chinese website!