使页面滚动到指定元素+优化+API介绍(JS动画)

前言

1  使用的API简介

2  初版

  • 代码及思路如下:
    //1 点击导航跳到指定位置第一步,获取所有的a标签
    let aTags=document.querySelectorAll("nav.menu ul li a") 
        //console.log(aTags)
    //2 点击导航跳到指定位置第二步遍历a标签
    for(let i=0;i<=aTags.length;i++){
        aTags[i].onclick=function(x){
        x.preventDefault();  //阻止a标签默认的跳转
        //console.log(x.currentTarget);
        let a=x.currentTarget;
        let href=a.getAttribute("href"); //找到href中的内容,如果href中时一个锚点则返回#siteSkill
        //console.log(href);
        let element=document.querySelector(href); //找到内容中的锚点对应ID的标签,如对应的锚点名为#siteSkill,则返回<section class=​"skills" id=​"siteWorks">​…​</section>​
        //console.log(element);
        let top=element.offsetTop;     //获取元素到页面最顶点的高度(不会随着页面滚动变化的高度)
        //console.log(top);
        window.scrollTo(0,top-80);
        }
    }
  • 缺点:跳转太快,没有过渡,影响用户体验

3  优化

  • 优化后代码如下:

猜你喜欢

转载自www.cnblogs.com/nolaaaaa/p/9021967.html