0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

jQueryなしでスクロール

Posted at

ページ外リンク


// 現在表示されているディスプレイサイズを判定
const pcDisplayFlag: boolean = window.matchMedia('(min-width: 960px)').matches
// 移動させたい位置の値を決める要素を取得
const headerElement = pcDisplayFlag ? document.getElementById('pcHeader') : document.getElementById('mobileHeader')

const hash: string = window.location.hash ? window.location.hash.substring(1) : ''
if (hash) {
    const targetElement = document.getElementById(hash)
    if (headerElement && targetElement) {
    const rectangular = targetElement.getBoundingClientRect()
    window.scrollTo({
        top: window.pageYOffset + rectangular.top - headerElement.clientHeight - 30,
        behavior: 'smooth'
    })
    }
}

ページ内リンク


// 現在表示されているディスプレイサイズを判定
const pcDisplayFlag: boolean = window.matchMedia('(min-width: 960px)').matches
// 移動させたい位置の値を決める要素を取得
const headerElement = pcDisplayFlag ? document.getElementById('pcHeader') : document.getElementById('mobileHeader')

function linkScroll(event: Event, hash: string | undefined) {
    event.preventDefault()
    if (hash) {
    const targetElement = document.getElementById(hash)
    if (headerElement && targetElement) {
        const rectangular = targetElement.getBoundingClientRect()
        window.scroll({
        top: window.pageYOffset + rectangular.top - headerElement.clientHeight - 30,
        behavior: 'smooth'
        })
    }
    }
}

// ページ内リンク
const hashLinks = document.querySelectorAll('a[href^="#"]')
if (hashLinks.length > 0) {
    hashLinks.forEach((link) => {
    link.addEventListener('click', (event) => {
        linkScroll(event, link.getAttribute('href')?.substring(1))
    })
    })
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?