原生js实现页面滚动到指定dom节点
【案例】
<html lang="en">
<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>滚动到指定的div案例</title>
<style>
.box {
height: 1000px;
background-color: #bfa;
border: 1px solid #000;
}
.myBox {
margin-top: 500px;
height: 200px;
background-color: deepskyblue;
}
</style>
</head>
<body>
<div class="box">
<button id="gun">滚</button>
<div class="myBox">目标元素</div>
</div>
<script>
function heightToTop(ele) {
//ele为指定跳转到该位置的DOM节点
let bridge = ele;
let root = document.body;
let height = 0;
//关键点1:这里使用do while 累加偏移的高度
do {
height += bridge.offsetTop;
bridge = bridge.offsetParent;
} while (bridge !== root)
return height;
}
//按钮点击时
let gunBtn = document.querySelector("#gun")
let targetEle = document.querySelector(".myBox")
gunBtn.addEventListener('click', function () {
//关键点2:使用window的滚动方法
window.scrollTo({
top: heightToTop(targetEle),
behavior: 'smooth'
})
// window.scrollTo({
// top: 0,
// behavior: 'smooth'
// })
})
</script>
</body>
</html>