html中使用JQ自定义锚点偏移量

问题:一般情况下使用href跳转达到效果。如果页面中头部固定住了,点击瞄点的时候自动是最上面,头部会给它覆盖掉一部分,所以要在点击之后额外再加头部高度

html 复制代码
  <a href="#aa">Technical Documents</a>
  <div id="aa">aaaaaaaaaaa</div>

js

javascript 复制代码
// 当点击瞄点时执行滚动动作
$('a[href="#aa"]').on('click', function(e) {
  e.preventDefault(); // 阻止默认行为
  var targetPosition = $('#aa').offset().top; // 获取瞄点位置
  $('html, body').animate({
    scrollTop: targetPosition + 100 // 滚动到瞄点位置再额外往下滚动100px
  }, 800); // 滚动持续时间
});

如果有多个的话,封装js

javascript 复制代码
// 当点击瞄点时执行滚动动作
function scrollToAnchor(anchor, offset) {
  $('a[href="' + anchor + '"]').on('click', function(e) {
    e.preventDefault(); // 阻止默认行为
    var targetPosition = $(anchor).offset().top; // 获取瞄点位置
    $('html, body').animate({
      scrollTop: targetPosition - offset // 滚动到瞄点位置再额外往下滚动指定的偏移量
    }, 800); // 滚动持续时间
  });
}

// 使用封装的函数
scrollToAnchor('#aa', 200);
相关推荐
Bigger2 分钟前
后端拒写接口?前端硬核自救:纯前端实现静态资源下载全链路解析
前端·浏览器·vite
BD_Marathon17 分钟前
【JavaWeb】路径问题_前端绝对路径问题
前端
lionliu051922 分钟前
WebAssembly (Wasm)
java·开发语言·wasm
咸鱼加辣25 分钟前
【java面试题】springboot的生命周期
java·开发语言·spring boot
Billow_lamb27 分钟前
MyBatis Plus 中常用的插件列表
java·mybatis
程序猿DD1 小时前
人工智能如何改变 Anthropic 的工作方式
java·后端
C雨后彩虹1 小时前
任务总执行时长
java·数据结构·算法·华为·面试
whyfail1 小时前
Vue原理(暴力版)
前端·vue.js
桦说编程1 小时前
Guava Forwarding系列类详解——装饰器模式实战
java·后端·设计模式