ps:本人菜鸟一枚,仅记录工作中遇到的问题,还请广大网友多多包涵,不喜勿喷,谢谢~
正文最近在项目中遇到一个问题,需要根据当前是几月份来动态展示第一列的月份。这个时候首先给table外嵌套一层div,让table可以左右滚动,然后根据当前月份来固定某列,下面是详细代码
1、html代码
<div class="tablebox" id="tablebox">
<table cellpadding="6">
<tr>
<td>1月</td>
<td>2月</td>
<td>3月</td>
<td>4月</td>
<td>5月</td>
<td>6月</td>
<td>7月</td>
<td>8月</td>
<td>9月</td>
<td>10月</td>
<td>11月</td>
<td>12月</td>
</tr>
<tr>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
</tr>
<tr>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
</tr>
<tr>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
<td>267,500,000</td>
</tr>
</table>
</div>
<div class="co">
列数:<input type="number" id="num">
<button onclick="position()">定位到此列</button>
</div>
2、css代码
.tablebox {
margin: 50px auto;
width: 400px;
overflow-x: scroll;
}
table {
width: 100%;
border-collapse: collapse;
}
table thead tr {
background-color: #f5f5f6;
}
table tr>td,
table tr>th {
border: 1px solid #f2f2f2;
text-align: left;
/* padding: 0.02rem 0 0.02rem 0.1rem; */
}
.co {
margin: 0 auto;
text-align: center;
}
3、js代码
function position() {
let input = document.getElementById('num')
initTableDis('tablebox',input.value)
}
/*
* elId:元素id名(嵌套在table标签元素外面的那个div的id名)
* n: 代表表格对应到第几列
*/
function initTableDis(elId, n = 1) {
let el = document.getElementById(elId)
// 获取table标签元素
let table = el.querySelector('table')
if (!table) {
console.error('找不到该元素')
}
// 获取table表头里的所有td元素
let tds = table.querySelector('tr').querySelectorAll('td')
let sum = 0
for (let i = 0; i < new Number(n)-1; i++) {
// 当前td的宽度
if (tds[i]) {
sum += tds[i].offsetWidth
}
}
el.scrollLeft = sum
}