问题
页面中的table横向滚动,用户要求页面一加载就滚动到具体列位置
解决方法
所有html标签自带scrollIntoView()方法,可以定位到你所要去的位置
代码
<script>
// 横向滚动到table表中指定文字中间位置
function clickThree() {
//获取td元素,找到你想去的文字位置
var td = document.getElementsByTagName('td');
for(let i = 0 ;i < td.length ; i++){
if(td[i].innerText == '第20列'){
//可视化窗口会移动到该位置
td[i].scrollIntoView({block: "nearest", inline: "center"});
break;
}
}
}
</script>
<button onclick="clickThree()">GO</button>
<div style="overflow-x: auto; width:800px;">
<table class="gridtable">
<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>
<td>第13列</td>
<td>第14列</td>
<td>第15列</td>
<td>第16列</td>
<td>第17列</td>
<td>第18列</td>
<td>第19列</td>
<td>第20列</td>
<td>第21列</td>
<td>第22列</td>
<td>第23列</td>
<td>第24列</td>
<td>第25列</td>
<td>第26列</td>
<td>第27列</td>
<td>第28列</td>
<td>第29列</td>
<td>第30列</td>
<td>第31列</td>
<td>第32列</td>
<td>第33列</td>
</tr>
</table>
</div>
<style>
table.gridtable {
height: 100px;
width:800px;
font-family: verdana,arial,sans-serif;
font-size:11px;
color:#333333;
border-width: 1px;
border-color: #666666;
border-collapse: collapse;
}
table.gridtable th {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #dedede;
}
table.gridtable td {
border-width: 1px;
padding: 20px 50px;
border-style: solid;
border-color: #666666;
background-color: #ffffff;
}
</style>
效果图
scrollIntoView方法介绍
用途:scrollIntoView 是 HTMLElement 集合下的一个 API,每一个 HTML 元素都拥有这个 API。它的作用就和字面意思一样:滚动到可视区
方法参数介绍:
element.scrollIntoView(); // 等同于 element.scrollIntoView(true)
element.scrollIntoView(alignToTop); // Boolean 型参数
element.scrollIntoView(scrollIntoViewOptions); // Object 型参数
参数解释:
-
alignToTop:它是一个 Boolean 值,它用来规定元素出现在可视区后与可视区的对齐方式,为 true
代表顶端对齐,false 代表低端对齐。 -
scrollIntoViewOptions:它是一个对象,该参数主要是配置元素的动画效果以及位置的,它有一下 3 个属性:
behavior:它定义元素出现在可视区内过程的动画,有 auto 和 smooth 两种选择。
block:定义元素的垂直方向的对齐方式,有"start", “center”, “end”, 或 “nearest” 4 个选项,默认start。
inline:定义元素水平对齐方式,有"start", “center”, “end”, 或 “nearest"4 个选项,默认"nearest”。
以上摘自这位博主!!!大家详细请看这位
https://zhuanlan.zhihu.com/p/525742938?utm_id=0