| 選擇器 | 匹配條件 | 不匹配條件 |
|---|---|---|
| :visible | 元素佔據版面空間(寬/高 > 0) | display:none、type=hidden、width/height=0、祖先元素隱藏 |
| :hidden | 上述任一條件成立 | visibility:hidden、opacity:0、位置在螢幕外 |
<tr id="one" style="display:none"><td>1</td></tr> <!-- :hidden -->
<tr id="two" style="visibility:hidden"><td>2</td></tr> <!-- :visible (佔空間) -->
<tr id="three"><td>3</td></tr> <!-- :visible -->
$('tr:hidden'); // 選中 #one
$('tr:visible'); // 選中 #two, #three
:visible/:hidden 只關心 盒模型佔據空間,不關心 `visibility`、`opacity`、`clip-path`、層級遮擋。
// ❌ 慢:全域掃描
$('div:visible')
// ✅ 快:先 ID/Class 選擇,再過濾
$('#container').find('div').filter(':visible')
// ✅ 更快:原生 CSS + JS 判斷
const visibleDivs = [...document.querySelectorAll('#container div')]
.filter(el => el.offsetWidth > 0 || el.offsetHeight > 0 || el.getClientRects().length);
function isVisible(el) {
if (!el) return false;
const style = getComputedStyle(el);
if (style.display === 'none') return false;
if (style.visibility === 'hidden') return false; // 依需求決定是否視為隱藏
if (el.offsetWidth === 0 && el.offsetHeight === 0 && el.getClientRects().length === 0) return false;
// 遞歸檢查祖先
let parent = el.parentElement;
while (parent) {
const pStyle = getComputedStyle(parent);
if (pStyle.display === 'none' || pStyle.visibility === 'hidden') return false;
parent = parent.parentElement;
}
return true;
}
$('#form').on('submit', function(e) {
const invalid = $(this).find('input:visible[required]').filter((i, el) => !el.value).length;
if (invalid) { e.preventDefault(); alert('請填寫必填欄位'); }
});
function togglePanel($panel) {
if ($panel.is(':visible')) $panel.slideUp();
else $panel.slideDown();
}
@media print {
.no-print { display: none !important; }
}
// JS 中
$('.no-print').filter(':visible').hide(); // 列印前隱藏