在 jQuery 中,判断一个元素是否隐藏有 多种方法,适用于不同场景(CSS display:none、visibility:hidden、opacity:0 等)。下面整理一份 全面指南。
1️⃣ 使用 :hidden / :visible 选择器
示例
<div id="box1" style="display:none;">隐藏元素</div>
<div id="box2">显示元素</div>
if ($('#box1').is(':hidden')) {
console.log('box1 是隐藏的')
}
if ($('#box2').is(':visible')) {
console.log('box2 是可见的')
}
✅ 特点:
:hidden会检查元素本身及其父元素是否隐藏:visible与:hidden相反- 包括
display:none、width:0、height:0、父元素隐藏等情况
2️⃣ 使用 .css('display')
检查元素的 display 属性:
if ($('#box1').css('display') === 'none') {
console.log('元素 display:none')
}
✅ 注意:
- 只能判断 display 属性
- 对
visibility:hidden或opacity:0无效
3️⃣ 使用 .is(':hidden') 与 .is(':visible') 结合父元素
const el = $('#box1')
if (el.is(':hidden')) {
console.log('元素隐藏(包括父元素影响)')
}
:hidden会自动考虑 父元素是否隐藏- 推荐用于大多数判断场景
4️⃣ 使用 .width() 或 .height()
const el = $('#box1')
if (el.width() === 0 && el.height() === 0) {
console.log('元素隐藏或尺寸为0')
}
✅ 说明:
- 当元素 不可见但没有 display:none 时(如
opacity:0或visibility:hidden),宽高可能为0 - 可结合 CSS 判断使用
5️⃣ 使用 .prop('offsetParent')
const el = $('#box1')
if (!el.prop('offsetParent')) {
console.log('元素隐藏(display:none 或父元素隐藏)')
}
✅ 说明:
offsetParent为 null 表示元素在布局中不可见- 对
visibility:hidden无效
6️⃣ 使用 .is(':hidden') 判断复合条件
如果你希望判断元素是否完全不可见(包括 display、visibility、opacity):
function isCompletelyHidden($el) {
return $el.is(':hidden') || $el.css('visibility') === 'hidden' || $el.css('opacity') === '0';
}
if (isCompletelyHidden($('#box1'))) {
console.log('元素完全不可见')
}
✅ 特点:
- 更严格判断
- 包含三种常见隐藏方式
7️⃣ 总结各种方法适用场景
| 方法 | 可见性类型 | 是否考虑父元素 | 优点 |
|---|---|---|---|
:hidden / :visible | display:none、width/height=0 | 是 | 推荐用于大多数场景 |
.css('display') | display:none | 否 | 简单直接,精确判断 display |
.width()/height() | 尺寸为0 | 否 | 判断元素大小 |
.prop('offsetParent') | display:none/父隐藏 | 是 | 判断元素是否在布局中显示 |
| 自定义函数(visibility/opacity) | display:none + visibility:hidden + opacity:0 | 否 | 判断元素完全不可见 |
8️⃣ 小技巧
- 判断元素显示再执行动画:
if ($('#box1').is(':visible')) {
$('#box1').fadeOut()
}
- 判断父元素隐藏:
if ($('#box1').parents(':hidden').length > 0) {
console.log('父元素隐藏,子元素不可见')
}
- 综合判断:
function isHidden($el) {
return $el.is(':hidden') || $el.css('visibility') === 'hidden' || $el.css('opacity') === '0';
}
发表回复