当前位置:Gxlcms > JavaScript > JavaScript中style.display属性怎么使用

JavaScript中style.display属性怎么使用

时间:2021-07-01 10:21:17 帮助过:43人阅读

style.display属性是Style对象的display属性,Style对象用于自由更改元素的样式。例如,您可以添加各种样式,比如元素的高度和宽度,颜色和背景等。

我们来看看display属性

display属性具有指定元素的显示样式的作用。

不显示元素,或者作为块元素显示,或者可以指定各种显示方法

style.display属性的基本用法

我们来看代码如下

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<meta charset="utf-8">
</head>
<body>
<img id="style1" src="img/girl.jpg" width="150" height="150">
    <br>
    <input type="button" value="Hide" onclick="hide();"/>
    <br>
    <input type="button" value="Show" onclick="show();"/>

</body>
<script>
    function hide() {
        var e = document.getElementById("style1");
        e.style.display = "none";
    }
    function show(){
        var e = document.getElementById("style1");
        e.style.display = "block";
    }
</script>
</html>

在上面的代码中使用style.display属性显示或隐藏图像。

首先,img标签用于显示图像,在图像下创建了两个按钮。

第一个按钮是隐藏图像的Hide按钮。

第二个按钮是show按钮可再次显示图像。

为“Hide”按钮的onclick属性指定了hide函数。

hide函数首先使用getElementById方法获取image元素。

获取image元素后,我们访问该元素的style.display属性并指定字符串none。

您可以通过替换值none来隐藏元素。

点击hide按钮图片隐藏

微信截图_20190107142556.png

单击hide按钮将清除图像消失并提升按钮的位置。

相反,单击“显示”按钮,图像将重新出现。

show函数是为Show按钮的onclick属性指定的。

与hide函数一样,show函数在使用getElementById方法获取image元素后访问style.display属性。

然后,代替字符串block,通过这样做,可以显示图像块,并且再次显示图像。

微信截图_20190107142812.png

display和visibility有什么区别?

在上面的示例代码中,使用style对象的display属性更改图像的显示设置。

但是,除了display属性之外,还可以使用visibility属性显示或隐藏图像。

代码如下

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<meta charset="utf-8">
</head>
<body>
    <img id="drag1" src="img/flowers.jpg" width="150" height="150">
    <br>
    <input type="button" value="Hide with DISPLAY" onclick="hide1();"/>
    <br>
    <input type="button" value="Hide with VISIBILITY" onclick="hide2();"/>

</body>
<script>
    function hide1() {
        var e = document.getElementById("drag1");
        e.style.display = "none";
    }
 
    function hide2() {
        var e = document.getElementById("drag1");
        e.style.visibility = "hidden";
    }
</script>
</html>

在上面的代码中,我们创建了两个按钮来隐藏图像。

第一个是Hide with DISPLAY按钮,它使用与以前相同的display属性。

第二个是Hide with VISIBILITY按钮,使用visibility属性隐藏。

微信截图_20190107143532.png

为第二个按钮的onclick属性指定了hide2函数。

hide2函数使用getElementById方法获取image元素并访问style.visibility属性。

然后,通过替换隐藏的字符串,隐藏图像。

如前所述,单击按钮将导致图像消失,图像下方的按钮将上升。

但是,如果使用visibility的单击按钮,则有图像的部分将仅为空白,空间将会保留。

微信截图_20190107143836.png

可以明显看到按钮保持在原来位置,图像的位置空白且空间保留。

以上就是JavaScript中style.display属性怎么使用的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行