扫码关注官方订阅号
使用javascript判断一个元素是块级元素还是内联元素的方法,主要是为了显示或隐藏一个元素,该怎么做?
学习是最好的投资!
@etianqq 按照你的思路,稍微做了一些兼容,主要封装了一个获取元素的属性的函数getStyle(obj, attr),因为getComputedStyle实际上是火狐使用的。
function getStyle(obj, attr) { if (obj.currentStyle) { return obj.currentStyle[attr]; } else { return getComputedStyle(obj, false)[attr]; } }
html
<p id="block">element1 element1 element1</p> <span id="span">element2 element2 element2 </span>
js
var block=document.getElementById('block'); var span=document.getElementById('span'); console.log(getStyle(block,'display')) console.log(getStyle(span,'display')) function getStyle(obj, attr) { if (obj.currentStyle) { return obj.currentStyle[attr]; } else { return getComputedStyle(obj, false)[attr]; } }
output
element1: block element2: inline
利用Window.getComputedStyle()取得元素的style对象,然后查看display属性。HTML:
<p id="elt1">element1</p> <span id="elt2">element2</span>
JS:
var elt = document.getElementById("elt1"); console.log(window.getComputedStyle(elt).display); elt = document.getElementById("elt2"); console.log(window.getComputedStyle(elt).display);
Output:
element1:block element2:inline
毫无应用场景的问题
设置css类 hidden.
.hidden, [hidden] { display: none !important; }
隐藏的元素add一个hidden属性, 显示的时remove hidden属性。这样就不用纠结了。
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
@etianqq 按照你的思路,稍微做了一些兼容,主要封装了一个获取元素的属性的函数getStyle(obj, attr),因为getComputedStyle实际上是火狐使用的。
html
js
output
利用Window.getComputedStyle()取得元素的style对象,然后查看display属性。
HTML:
JS:
Output:
毫无应用场景的问题
设置css类 hidden.
隐藏的元素add一个hidden属性, 显示的时remove hidden属性。这样就不用纠结了。