在互動介面中,常需要根據元素是否顯示來切換樣式、文字或圖示。jQuery 提供了多種方式來判斷元素目前是否可見。
if ($(this).next().is(':visible')) {
console.log('目前可見');
} else {
console.log('目前隱藏');
}
if ($(this).next().css('display') === 'none') {
console.log('目前隱藏');
} else {
console.log('目前可見');
}
const $cn = $(this).next();
$cn.slideToggle('fast');
三種方式各有用途::visible 語意清楚,css('display') 適合檢查具體樣式,slideToggle 則適合直接切換顯示狀態。