ホームページにボタンを追加しました。ユーザーがこのボタンをクリックすると、ページが参照する適切なセクション(私の場合は私のホームページのショップの部分)にスクロールします。ユーザーがボタンをクリックしたときにページをスクロールするコードを挿入するにはどうすればよいですか?ユーザーがボタンをクリックしたときにページをスクロールダウンさせるにはどうすればよいですか?
私のウェブサイトは、hintdrop.com
ホームページにボタンを追加しました。ユーザーがこのボタンをクリックすると、ページが参照する適切なセクション(私の場合は私のホームページのショップの部分)にスクロールします。ユーザーがボタンをクリックしたときにページをスクロールするコードを挿入するにはどうすればよいですか?ユーザーがボタンをクリックしたときにページをスクロールダウンさせるにはどうすればよいですか?
私のウェブサイトは、hintdrop.com
あなたはフラグメント識別子を探しています。
スクロールするセクションにid
属性を追加します。
例:次に<section id="shop"> ... </section>
、href
属性で、アンカー<a>
代わりのボタンを使用します。
例:<a href="#shop">Shop</a>
簡単な例:
#shop {
margin-top: 300vh;
background-color: tomato;
height: 100vh;
position: relative;
}
#shop::after {
content: 'Shop Content';
position: absolute;
color: white;
font-size: 3em;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
<a href="#shop">Shop</a>
<section id="shop"></section>
スムーズなスクロールが望まれる場合は、scrollIntoView
はそうのように使用することができます。
document.querySelector('#shopBtn').addEventListener('click', function() {
document.querySelector('#shop').scrollIntoView({
behavior: 'smooth'
});
});
#shop {
margin-top: 300vh;
background-color: tomato;
height: 100vh;
position: relative;
}
#shop::after {
content: 'Shop Content';
position: absolute;
color: white;
font-size: 3em;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
<button id="shopBtn">Shop</button>
<section id="shop"></section>
また、ahrefを使用してIDを指定すると、クリックすると特定のセクションに移動することができます。
最も簡単な答え:idをdivタグまたは他のタグに作成し、アンカータグまたはhrefタグにIDの名前をリンクします。
例:
<!--remember that ID links inside your html tag, should always have a hashtag (#)-->
<a href="#thisismydiv">JUMP TO MY DIVISION</a>
<!--your codes--->
<div id="thisismydiv">I am div!</div>
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView –