美文网首页
锚点跳转

锚点跳转

作者: autumn_3d55 | 来源:发表于2022-01-13 15:20 被阅读0次

    1.锚点跳转

    可使用scrollIntoView()方法将调用它的元素滚动到浏览器窗口的可见区域

    2.语法

    element.scrollIntoView(); // 等同于element.scrollIntoView(true)
    element.scrollIntoView(alignToTop); //布尔参数
    element.scrollIntoView(scrollIntoViewOptions); //对象参数

    3.语法参数

    • alignToTop [可选],目前之前这个参数得到了良好的支持
    • true 元素的顶部将对齐到可滚动祖先的可见区域的顶部。对应于scrollIntoViewOptions: {block: "start", inline: "nearest"}。这是默认值
    • false 元素的底部将与可滚动祖先的可见区域的底部对齐。对应于scrollIntoViewOptions: {block: "end", inline: "nearest"}。
    • scrollIntoViewOptions [可选],目前这个参数浏览器对它的支持并不好,可以查看下文兼容性详情
    • behavior [可选]定义过渡动画。"auto","instant"或"smooth"。默认为"auto"。
    • block [可选] "start","center","end"或"nearest"。默认为"center"。
    • inline [可选] "start","center","end"或"nearest"。默认为"nearest"。

    说明

    instant:立即

    smooth:平滑滚动

    nearest:最近点

    4.使用

    4.1 方法一,通过方法跳转

    <button @click="toHref('#ranking')">//传入要跳转的id选择器
    <div class="ranking" id="ranking">
    
    //锚点跳转
        toHref(id) {  //toHref是绑定的点击事件名称
            const returnEle = document.querySelector(id);  //productId是将要跳转区域的id
            if (!!returnEle) {
              returnEle.scrollIntoView({behavior: "smooth", block: "nearest", inline: "nearest"}); // true 是默认的
            }
          }
    

    4.2 方法二,使用a标签和#跳转

    1、a标签上写上一个id名(即将跳转到的区域的名称)

    <div><a href="#productid">产品介绍</a></div>   
    
    

    2、在你点击跳转的产品介绍详情区域的最外层div上添加一个id;

    <div class="product" id="productId"></div>
    

    相关文章

      网友评论

          本文标题:锚点跳转

          本文链接:https://www.haomeiwen.com/subject/wsbncrtx.html