Home >Web Front-end >JS Tutorial >How to hide and display div in javascript

How to hide and display div in javascript

青灯夜游
青灯夜游Original
2021-04-26 17:35:188686browse

Setting method: 1. Use the display attribute of the style object, the value is "none" to hide the div element, and the value is "block" to display the element; 2. Use the visibility attribute of the style object, the value is "hidden" " can hide the div element, and the value "visible" can display the element.

How to hide and display div in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

There are two ways to hide and show divs in JS:

Method 1: Set the display attribute in the element style object

var t = document.getElementById('test');//选取id为test的div元素
t.style.display = 'none';// 隐藏选择的元素
t.style.display = 'block';// 以块级样式显示

Method 2: Set the visibility attribute in the element style object

var t = document.getElementById('test');//选取id为test的div元素
t.style.visibility = 'hidden';// 隐藏元素
t.style.visibility = 'visible';// 显示元素

The difference between these two methods is: setting the display to hide does not occupy the original position , and the element position is still occupied after hiding through visibility.

The effect is as follows:
How to hide and display div in javascript

The first way hides the front

How to hide and display div in javascript

Do not occupy the original position after hiding

How to hide and display div in javascript

##The second method hides the previous one

How to hide and display div in javascript

After hiding in the two ways, it still occupies the original position.

The complete code is as follows:

    <script>
        function fn1(){
            var t = document.getElementById(&#39;test&#39;);
            if(t.style.display === &#39;none&#39;) {
                t.style.display = &#39;block&#39;;// 以块级元素显示
            } else {
                t.style.display = &#39;none&#39;; // 隐藏
            }
        }

        function fn2(){
            var t = document.getElementById(&#39;test&#39;);
            if(t.style.visibility === &#39;hidden&#39;) {
                t.style.visibility = &#39;visible&#39;;
            } else {
                t.style.visibility = &#39;hidden&#39;;
            }
        }
    </script>



	<div>
	    这是一个将要隐藏的DIV。<br>
	    这是一个将要隐藏的DIV。<br>
	    这是一个将要隐藏的DIV。<br>
	    这是一个将要隐藏的DIV。<br>
	</div>
	<button>第一种方式</button>
	<button>第二种方式</button>
[Recommended learning:

javascript advanced tutorial]

The above is the detailed content of How to hide and display div in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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