2017-12-29 14 views
0

ホームページにボタンを追加しました。ユーザーがこのボタンをクリックすると、ページが参照する適切なセクション(私の場合は私のホームページのショップの部分)にスクロールします。ユーザーがボタンをクリックしたときにページをスクロールするコードを挿入するにはどうすればよいですか?ユーザーがボタンをクリックしたときにページをスクロールダウンさせるにはどうすればよいですか?

私のウェブサイトは、hintdrop.com

+0

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView –

答えて

1

あなたはフラグメント識別子を探しています。

スクロールするセクションに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>

0

また、ahrefを使用してIDを指定すると、クリックすると特定のセクションに移動することができます。

0

最も簡単な答え: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> 
関連する問題