a标签锚点平滑跳转 && 使用scrollIntoView && 注:2022-09-06更新

使用 scrollIntoView 实现锚点平滑跳转

html

<button class="btn">跳转</button>

<!-- ... -->

<div class="container">锚点区域</div>

js

document.querySelector('.btn').onclick = function (){
     document.querySelector('.container').scrollIntoView({
         behavior: "smooth", 
         block: "center", 
         inline: "nearest"
     })
}

scrollIntoView 属性

  • behavior 定义动画过渡效果, "auto"或 "smooth" 之一。默认为 "auto"
  • block 定义垂直方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "start"
  • inline 定义水平方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "nearest"

 

注:scrollTo

如果想滚动到屏幕指定位置可以使用 scrollTo(xpos, ypos)

window.scrollTo(0, 100px)
 

 

2022-09-06之前代码

一、创建锚点

<div class="header" id="top">//终点标签,添加一个id

<a href="#top" class="fixed_top_a">^</a>//a标签href添加#id

锚点跳转很生硬,很不友好,找了两种平滑的跳转方法

二、平滑跳转

复制代码
$('a[href*=#],area[href*=#]').click(function () {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var $target = $(this.hash);
      $target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');
      if ($target.length) {
        var targetOffset = $target.offset().top;
        $('html,body').animate({
          scrollTop: targetOffset
        },
          1000);
        return false;
      }
    }
  });

  https://blog.csdn.net/u012011360/article/details/78972858//原文链接
复制代码

 

复制代码
$(".fixed_btn").click(function () {

    $("html, body").animate({scrollTop: $($(this).attr("href")).offset().top -20+ "px"}, 500);

    return false;

});

https://blog.csdn.net/never_tears/article/details/53377123//原文链接
复制代码

 

  • html
  • js
  • scrollIntoView 属性
  • 注:scrollTo
posted @   时光凉忆  阅读(1815)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
点击右上角即可分享
微信分享提示