点击页面内自动跳转(js&缓动)

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>
	<!--手动二十个<br>-->
    <p id="anchorone">道阻且长,行则将至.</p>
    <!--手动二十个<br>-->
    <p id="anchortwo" >如果你给我的,和你给别人的是一样的,那我就不要了.</p>
    <!--手动二十个<br>-->
    <p id="anchorthree" >♥若没有栖息的地方,到哪里都是在流浪.</p>
    <!--手动二十个<br>-->
    啦啦啦
</body>
</html>
复制代码

css部分

/* 清除掉部分元素的默认格式 */
*{
  list-style: none;
  padding: 0;
  margin: 0;
  text-decoration: none;
}
.clearfix::after{
  content: '';
  display: block;
  clear: both;
}
/* 让导航栏脱离文档流,跳转时会对文字有遮盖,因此用js实现 */
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) // 创建一个新的缓动函数,参数是 'coords'.
        .to({ y: targetTop }, 500) // 在一秒内移动到坐标300 200.
        .easing(TWEEN.Easing.Quadratic.InOut) // 用淡入功能做一个平滑的动画.
        .onUpdate(function () { //更新 'coords'后调用.
            // 用csstranslation通过'coords'移动目标到指定位置.
            window.scrollTo(0, coords.y);
        })
        .start(); // 开始.
    window.scrollTo(0,top-60)
    }
}
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值