HTML跳转页面指定位置的几种方法

由于页面显示的信息总是有限的,因此我们需要得以跳转到页面指定位置的实现

  1. 纯html实现
    1. 跳转时机:<a href="#anchorName">点击跳转到name为anchorName的位置</a>
    2. 埋锚点:<a name="anchorName">a标签的锚点</a>,<p id="anchorName">以id为标记的锚点</p>
    3. 分析:当点击a标签就会跳到锚点处,没有缓冲效果,体验一般,而且url里会添加"#anchorName"。这在SPA应用里是不可接收的,因为这影响了路由配置。刷新页面无效。
  2. JavaScript辅助(window.scrollTo方法)
    1. window.scrollTo({ top,left ,behavior}),分别为数字、数字、字符串。指定跳转到距离文档顶部、左边的距离,以及跳转效果(smooth、instant)
    2. 跳转时机:添加事件监听
    3. 获取元素到文档顶部的距离(offsetTop属性),offsetTop返回当前元素相对于其 offsetParent 元素的顶部的距离,因此我们要通过循环的方式累加来拿到距离文档最顶部的距离
function heightToTop(ele){
    //ele为指定跳转到该位置的DOM节点
    let bridge = ele;
    let root = document.body;
    let height = 0;
    do{
        height += bridge.offsetTop;
        bridge = bridge.offsetParent;
    }while(bridge !== root)

    return height;
}
//按钮点击时
someBtn.addEventListener('click',function(){
    window.scrollTo({
        top:heightToTop(targetEle),
        behavior:'smooth'
    })
})

两行方法比较起来,明显第二种更好点.

猜你喜欢

转载自blog.csdn.net/qq_40882724/article/details/81908148