解决网站表格在手机端太大的方案。
时间:2026-10-06 访问量:1001
假如我们的网站在发布新闻的时候,在后台插入了表格,表格可能比较大,在手机端如果100%的话,又显示得太小。所以我们考虑的是,在手机端自动可以左右滑动。
方案一:
例如:
<div class="news_content">{content:content}</div>这是新闻详情的代码。
通过数据库自动生成。
然后我们需要当有表格的时候,给表格添加一个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实现对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')) {
// 创建提示文字
const tip = document.createElement('div');
tip.className = 'd-block d-md-none';
tip.textContent = '你可以左右滑动查看表格更多信息';
// 创建包裹容器
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> 正在加载评论…