表格行 <tr> 設置 display: none 在舊版 IE/Edge 中不生效,甚至破壞表格布局。本文分析原因,提供三種穩健的跨瀏覽器隱藏方案。
<tr id="ReturnrReason" style="display: none">
<td>附件退回原因</td>
<td colspan="3">
<!-- 复选框列表 -->
</td>
</tr>
<tr id="ReturnrReasonNote" style="display: none">
<td>附件退回原因備注</td>
<td colspan="3">
<textarea id="ReturnRemarks"></textarea>
</td>
</tr>
// jQuery 切換顯示/隱藏
var show = $('#nextTransaction1 option:selected').text() === "退回制作附件";
$('#ReturnrReason, #ReturnrReasonNote').css('display', show ? '' : 'none');
<tr> 的默認 display 值是 table-row,而非 block。設置為 none 雖符合標準,但 IE ≤ 11 與舊版 Edge 將 <tr> 視為特殊渲染對象,display: none 會導致:
// CSS
tr.hidden-row { visibility: collapse; }
// JS
$('#ReturnrReason, #ReturnrReasonNote').toggleClass('hidden-row', !show);
collapse 支持有 Bug,現代版本已修復// 隱藏:將所有 td 內容包裹在隱藏容器中
function hideRow(rowId) {
$('#' + rowId).find('td').each(function() {
var $cell = $(this);
if (!$cell.data('original-content')) {
$cell.data('original-content', $cell.html());
$cell.html('<div style="display:none">' + $cell.html() + '</div>');
} else {
$cell.find('div').hide();
}
});
}
// 顯示
function showRow(rowId) {
$('#' + rowId).find('td div').show();
}
或更簡單:給 <td> 設置 display: none (但會破壞 colspan 布局)。
<tr id="ReturnrReason" hidden>...</tr>
// JS
document.getElementById('ReturnrReason').hidden = !show;
display 切換,不影響表格布局tr[hidden] { display: none }.table-row-hidden {
visibility: collapse; /* 現代瀏覽器 */
}
/* IE10- 降級:雖不完美但不破壞布局 */
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.table-row-hidden { display: none; }
}
// 使用
$('#ReturnrReason, #ReturnrReasonNote').toggleClass('table-row-hidden', !show);
$.fn.toggleTableRow = function(show) {
return this.each(function() {
var $tr = $(this);
if ('hidden' in this) { // 支持 HTML5 hidden
this.hidden = !show;
} else {
$tr.toggleClass('table-row-hidden', !show);
}
});
};
// 用法
$('#ReturnrReason, #ReturnrReasonNote').toggleTableRow(show);
掌握表格行隱藏的瀏覽器差異,是前端處理複雜表單交互的必修課。