LoginSignup
0
0

More than 1 year has passed since last update.

【rails入門】ページのスクロールに合わせて要素を動かす!

Last updated at Posted at 2022-04-21

完成したこんな感じ

scroll.gif

スクロールに応じて要素を左右に動かす!

コード

index.html
<div class="scroll">
    <div class="scroll-1">My name is Naoya.</div> <!-- 動かす要素 -->
    <div class="scroll-2">GeekSalon Fukuoka</div> <!-- 動かす要素 -->
</div>
<script>
    const scroll1 = document.querySelector('.scroll-1'); //要素取得
    const scroll2 = document.querySelector('.scroll-2'); //要素取得

    window.addEventListener('scroll', () => { //eventlistener定義
        scroll1.style.setProperty('--scroll',window.scrollY + 'px'); 
        //カスタムプロパティ --scroll の値にy軸方向のスクロール量を代入
        scroll2.style.setProperty('--scroll',window.scrollY + 'px');
        //カスタムプロパティ --scroll の値にy軸方向のスクロール量を代入
    })
</script>
index.css
.scroll{
    overflow: hidden; /*適当*/
}
.scroll-1{
    width: 500px; /*適当*/
    position: absolute;
    --scroll: 0; /*カスタムプロパティ(変数)宣言*/
    top: 50vh; /*適当*/
    left: var(--scroll);
    /*2行上で宣言してるカスタムプロパティの位置に移動させる。javascriptでカスタムプロパティの中身変更してる*/
}
.scroll-2{
    width: 500px; /*適当*/
    position: absolute;
    top: 60vh; /*適当*/
    --scroll: 0; /*カスタムプロパティ(変数)宣言*/
    right: var(--scroll);
    /*2行上で宣言してるカスタムプロパティの位置に移動させる。javascriptでカスタムプロパティの中身変更してる*/
}

解説

特になし

終わり
ばいちゃ

0
0
1

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