点击按钮,让页面滚动到指定位置的方法
1.喵点
2.ele.scrollIntoView()
关于scrollIntoView方法:
https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
ul {
margin: 20px 0;
}
.item-style {
height: 200px;
margin: 20px 0;
list-style: none;
border: 1px solid #d6d6d6;
font-size: 90px;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
}
.item-style:nth-child(2n) {
background-color: cornflowerblue;
}
.item-style:nth-child(2n+1) {
background-color: burlywood;
}
#input-style {
width: 100%;
height: 50px;
font-size: 40px;
}
.btn-style {
height: 60px;
border-radius: 4px;
border: none;
background-color: darkcyan;
font-size: 30px;
color: #fff;
margin: 20px;
}
</style>
</head>
<body>
<button onclick="moveCenter()" class="btn-style">
测试scrollIntoViewIfNeeded---true
</button>
<button onclick="moveOther()" class="btn-style">
测试scrollIntoViewIfNeeded---false
</button>
<button onclick="moveScrollIntoView(true)" class="btn-style">
测试scrollIntoView--true
</button>
<button onclick="moveScrollIntoView(false)" class="btn-style">
测试scrollIntoView--false
</button>
<button onclick="moveScrollIntoView({behavior: 'smooth', block: 'start', inline: 'nearest'})"
class="btn-style">
测试scrollIntoView--动画
</button>
<ul>
<li class="item-style">
1
</li>
<li class="item-style">
2
</li>
<li class="item-style">
3
</li>
<li class="item-style">
4
</li>
<input type="text" placeholder="请输入" id="input-style" />
<li class="item-style">
5
</li>
<li class="item-style">
6
</li>
<li class="item-style">
7
</li>
<li class="item-style">
8
</li>
</ul>
<script>
var ele = document.getElementById('input-style')
// 测试元素将在其所在滚动区的可视区域中居中对齐
function moveCenter() {
setTimeout(() => {
ele.scrollIntoViewIfNeeded()
},
500)
}
// 测试元素将与其所在滚动区的可视区域最近的边缘对齐
function moveOther() {
setTimeout(() => {
ele.scrollIntoViewIfNeeded(false)
},
500)
}
// 测试scrollIntoView, 根据可见区域最靠近元素的哪个边缘,
//元素的顶部将与可见区域的顶部边缘对准,或者元素的底部边缘将与可见区域的底部边缘对准。
function moveScrollIntoView(content) {
setTimeout(() => {
ele.scrollIntoView(content)
},
500)
}
</script>
</body>
</html>