---
# System prepended metadata

title: jQuery錨點
tags: [BTS, jQuery]

---

---
tags: jQuery
---
###### tags: `jQuery`
# jQuery錨點

```jQuery
$(".fda_list a[href^='#']").click(function (e) {
    e.preventDefault();

    var position = $($(this).attr("href")).offset().top - 155;

    $("body, html").animate({
        scrollTop: position;
    });
});

```
![](https://i.imgur.com/hRrj0Ay.png)

---
# 錨點加偏移量

```
 document.querySelectorAll('a.track').forEach(anchor => {
      anchor.addEventListener('click', function (e) {
        e.preventDefault();

        const targetId = this.getAttribute('href').substring(1);
        const target = document.getElementById(targetId);

        if (target) {
          const headerHeight = document.querySelector('header').offsetHeight; // 取得 header 的高度
          const offsetTop = target.getBoundingClientRect().top + window.scrollY; // 計算目標元素的位置

          window.scrollTo({
            top: offsetTop - headerHeight,
            behavior: 'smooth' // 平滑滾動效果
          });
        }
      });
    });

```