我们在页面操作时,有的时候会有一些操作在抽屉了,要定位到主页面的某个位置,这个时候可以使用Element.scrollIntoView()
MDN文档
样例:
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html {
width: 100vw;
box-sizing: border-box;
}
body {
width: 100%;
height: 100vh;
box-sizing: border-box;
padding: 0;
margin: 0;
overflow-x: hidden;
}
/* 滚动条整体部分 */
*::-webkit-scrollbar {
width: 3px;
height: 3px;
background-color: #eefefe;
}
/* 滚动滑块 */
*::-webkit-scrollbar-thumb {
background-color: indigo;
}
/* 外层轨道 */
*::-webkit-scrollbar-track,*::-webkit-scrollbar-corner {
background-color: #eababa;
}
/* 两端按钮 */
*::-webkit-scrollbar-button {
width: 0;
height: 0;
}
</style>
</head>
<body>
<ul id="list"></ul>
<script>
let list = document.getElementById("list")
for (let i = 1; i <= 200; i++) {
const element = document.createElement("li")
element.innerHTML = i
if(i === 100) {
element.id = "active"
element.style.background = "red"
}
list.append(element)
}
setTimeout(()=>{
document.getElementById("active").scrollIntoView({
"behavior": "smooth",
"block": "center",
"inline": "center"
})
}, 3000)
</script>
</body>
</html>