在前端开发中,经常会遇到需要给表格添加左右滑块的情况。这个功能的实现其实并不难,只需要一些简单的CSS样式和一些JavaScript代码即可。首先,我们需要对表格外层元素进行样式设置。使用CSS的ov...
在前端开发中,经常会遇到需要给表格添加左右滑块的情况。这个功能的实现其实并不难,只需要一些简单的CSS样式和一些JavaScript代码即可。
首先,我们需要对表格外层元素进行样式设置。使用CSS的overflow-x属性来控制表格的横向滚动条,如下所示:
table-wrapper {
overflow-x: scroll;
} table {
width: 100%;
}
table-wrapper {
max-width: ***px; /* 可以根据需要调整 */
} caption {
display: none;
} <script>
var wrapper = document.querySelector('.table-wrapper');
var table = document.querySelector('table');
wrapper.addEventListener('scroll', function(e) {
table.style.left = -wrapper.scrollLeft + 'px';
});
</script> <style>
.table-wrapper {
overflow-x: scroll;
max-width: ***px;
}
table {
width: 100%;
}
caption {
display: none;
}
</style>
<div class="table-wrapper">
<table>
<caption>这是一个表格标题</caption>
<thead>
<tr>
<th>列1</th>
<th>列2</th>
<th>列3</th>
</tr>
</thead>
<tbody>
<tr>
<td>内容1</td>
<td>内容2</td>
<td>内容3</td>
</tr>
<tr>
<td>内容4</td>
<td>内容5</td>
<td>内容6</td>
</tr>
<tr>
<td>内容7</td>
<td>内容8</td>
<td>内容9</td>
</tr>
</tbody>
</table>
</div>
<script>
var wrapper = document.querySelector('.table-wrapper');
var table = document.querySelector('table');
wrapper.addEventListener('scroll', function(e) {
table.style.left = -wrapper.scrollLeft + 'px';
});
</script>