<p id="text-link">クリックしたらスクロール</p>
<div class="box"></div>
<p id="text">----- ここまでスクロール -----</p>
<div class="box"></div>
html {
scroll-behavior: smooth;
}
.box {
height: 2000px;
width: 100%
}
// DOM取得
const $textLink = document.getElementById('text-link');
const $text = document.getElementById('text');
// id=text のブラウザの上からの位置を取得
const textTop = $text.getBoundingClientRect().top;
// id="text-link"を持つ要素がクリックされた場合
$textLink.addEventListener('click',()=> {
// スクロール
window.scrollTo({
top: textTop ,
left: 0,
behavior: 'smooth'
});
})
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.