前言最近更新了官网,发现用的是pug+jquery。有需要点击顶部导航跳转到另一个页面的指定位置。如下图,当我点击content1时,会跳转到页面中content1的位置。在类似的实现过程中很容易使用锚点a.pugul.clearfixlia(href="/page?about=1")Content1lia(href="/page?about=2")content2lia(href="/page?about=3")content3b.pug#about_1Content1#about_2content2#about_3content3a.js//锚链接跳转到指定位置var$root=$('html,body')//为了提高性能,缓存$('html,body')选择器。这样就不用每次点击都重新搜索functiontoWhere(id){if(!id)returnif(id===0){$root.animate({scrollTop:0},500)}else{$root.animate({scrollTop:$('#about_'+id).offset().top},500)}}//获取url中的hash值(about后面的数字)functiongetHash(hashName){varreg=newRegExp('(^|&)'+hashName+'=([^&]*)(&|$)','i')varr=window.location.search.substr(1).match(reg)if(r!=null){returnunescape(r[2])}return''}//函数执行(function(){$(function(){varaboutId=getHash('about')到哪里(关于我d)})})注意*关于锚点跳转,第一个条件是元素必须滚动,即:锚点元素在可滚动元素内部,但目前仍存在问题:*每次锚点被点击,会刷新页面,导致每次页面跳转锚点都从头开始滚动到指定位置,那么使用hash路由可以解决这个问题,*原因:hash出现在url中,但是它不会包含在HTTP请求中,对后端根本没有影响,所以更改hash不会在修改后重新加载页面:a.pugul.clearfixlia(href="/page#about=1")Content1lia(href="/page#about=2")content2lia(href="/page#about=3")content3b.jsvar$root=$('html,body');函数toWhere(id){if(!id||id===0){$root.animate({scrollTop:0},500)}constscrollHeight=$('#about_'+id).offset().top$root.animate({scrollTop:scrollHeight-60},600)}$(函数(){toWhere(window.location.hash.slice(1))})$(window).bind('hashchange',function(){varhashId=window.location.hash.slice(1);goToAnchor(hashId)});后续关于锚点链接的原理,这里有一篇关于锚点原理的文章叫cssdalao张新旭-锚点定位机制,挺长的。有兴趣的可以参考【参考文章】https://blog.csdn。net/qq_41314371/article/details/79447818https://www.zhangxinxu.com/wordpress/2013/08/url-anchor-html-anchor定位机制-应用-问题/
