html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./style.css">
<title>点击跳转到对应位置</title>
</head>
<body>
<ol class="topNavBar clearfix">
<li><a href="#anchorone">anchor1</a></li>
<li><a href="#anchortwo">anchor2</a></li>
<li><a href="#anchorthree">anchor3</a></li>
</ol>
<p id="anchorone">道阻且长,行则将至.</p>
<p id="anchortwo" >如果你给我的,和你给别人的是一样的,那我就不要了.</p>
<p id="anchorthree" >♥若没有栖息的地方,到哪里都是在流浪.</p>
啦啦啦
</body>
</html>
复制代码
css部分
*{
list-style: none;
padding: 0;
margin: 0;
text-decoration: none;
}
.clearfix::after{
content: '';
display: block;
clear: both;
}
ol.topNavBar{
position: fixed;
width: 100%;
}
body > ol {
background: cyan;
border: 1px solid transparent;
border-radius: 4px;
}
body > ol >li{
cursor: pointer;
float: left;
padding: 10px 10px;
}
body > ol > li > a{
color: rgb(99, 102, 58);
}
复制代码
js部分
<script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/17.2.0/Tween.min.js"></script>
function animate(time) {
requestAnimationFrame(animate);
TWEEN.update(time);
}
requestAnimationFrame(animate);
let aTags = document.querySelectorAll('ol.topNavBar > ol > li > a')
for(let i = 0; i<aTags.length ; i++){
aTags[i].onclick = function(x){
x.preventDefault();
let href = x.currentTarget.getAttribute('href');
let element = document.querySelector(href);
let top = element.offsetTop;
let currentTop = window.scrollY;
let targetTop = top - 60;
let distance = targetTop - currentTop;
if(distance<0){distance = -distance;}
var coords = { y: currentTop };
var tween = new TWEEN.Tween(coords)
.to({ y: targetTop }, 500)
.easing(TWEEN.Easing.Quadratic.InOut)
.onUpdate(function () {
window.scrollTo(0, coords.y);
})
.start();
window.scrollTo(0,top-60)
}
}
复制代码