
假如我們的網(wǎng)站在發(fā)布新聞的時候,在后臺插入了表格,表格可能比較大,在手機端如果100%的話,又顯示得太小。所以我們考慮的是,在手機端自動可以左右滑動。
方案一:
例如:
<div class="news_content">{content:content}</div>這是新聞詳情的代碼。
通過數(shù)據(jù)庫自動生成。
然后我們需要當有表格的時候,給表格添加一個div來將table包住 。
使用以下JQ:
<script type="text/javascript" charset="utf-8">
$(function () {
$('.news_content table').each(function () {
// 如果父級不是 .table-box 才包裹,避免重復包裹
if (!$(this).parent().hasClass('table-box')) {
$(this).wrap('<div class="table-box"></div>');
}
});
});
</script>第三步,我們需要在媒體查詢的手機端寫個table-box的CSS樣式:
.table-box {
width: 100%;
overflow-x: auto; /* 橫向滾動 */
-webkit-overflow-scrolling: touch; /* iPhone 慣性滾動 */
}
.table-box table {
min-width: 600px; /* 表格最小寬度,避免被壓縮變形 */
}這樣電腦端的table顯示100%寬度,寫上具體樣式就可以了。手機端則使用上面的CSS樣式就可以了。
方案二:
先是CSS,如果是BOOTSTRAP框架,自帶了此CSS, 如果不是,則不需要:
.table-responsive {
width: 100%;
overflow-x: auto;
-webkit-overflow-scrolling: touch; /* iOS 慣性滑動 */
}
.table-responsive table {
width: 100%;
border-collapse: collapse;
}然后是通過JS實現(xiàn)對table全部添加上提示用的
<div class="d-block d-md-none">You can slide the table to view more</div> <div class="table-responsive"> <table>...</table> </div>
以下是JS
<script type="text/javascript" charset="utf-8">
document.querySelectorAll('table').forEach(function (table) {
// 避免重復包裹
if (!table.parentElement.classList.contains('table-responsive')) {
// 創(chuàng)建提示文字
const tip = document.createElement('div');
tip.className = 'd-block d-md-none';
tip.textContent = '你可以左右滑動查看表格更多信息';
// 創(chuàng)建包裹容器
const wrapper = document.createElement('div');
wrapper.className = 'table-responsive';
// 插入提示文字(在 table-responsive 上方)
table.parentNode.insertBefore(tip, table);
// 插入 table-responsive 容器
table.parentNode.insertBefore(wrapper, table);
// 把 table 放進 wrapper
wrapper.appendChild(table);
}
});
</script>