只用一行代码:document.getElementById('xxx').scrollIntoView({ behavior: 'smooth' });
跳转到id为xxx的元素位置,这个id可以是标题的id也可以是元素的id。
<!DOCTYPE html>
<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>Document</title>
<style>
p {
margin-top: 500px;
}
</style>
<script>
window.onload = function () {
document.getElementById('xin').scrollIntoView({ behavior: 'smooth' });
}
</script>
</head>
<body>
<a href="#xin">点我跳转</a>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p id="xin">11111111</p>
<p>11111111</p>
</body>
</html>