表示場所によってサイドバーのテキストの色を付け替えよう!
Share
こんなことを説明しています!
- data属性でコンテンツとサイドバーを紐付けて、スクロールに応じてサイドバーのテキストの色が変わる実装方法
- scroll関数、each関数、scrollTop, offsetTopなどの位置情報を取得する関数の使用方法
解説動画
コードの解説
HTMLの記述
<div class="inner"> <h1 class="title">表示場所によってサイドバーのテキストの色を付け替えよう</h1> <div class="container"> <div class="article"> <div class="content" data="content1"> <img src='./img/img1.jpg' alt='' width='1200' height='600' loading='lazy'> <p>コンテンツ1</p> </div> <div class="content" data="content2"> <img src='./img/img2.jpg' alt='' width='1200' height='600' loading='lazy'> <p>コンテンツ2</p> </div> <div class="content" data="content3"> <img src='./img/img3.jpg' alt='' width='1200' height='600' loading='lazy'> <p>コンテンツ3</p> </div> </div> <div class="sidebar"> <p class="sidebar-item" data="content1">1. コンテンツ1</p> <p class="sidebar-item" data="content2">2. コンテンツ2</p> <p class="sidebar-item" data="content3">3. コンテンツ3</p> </div> </div> <div class="footer"> 別コンテンツ </div> </div>
CSSの記述
// ==================== // レイアウトを整えるcss // ==================== .inner { width: 100%; max-width: 1400px; margin: auto; padding: 0 40px; } .title { font-size: 40px; font-weight: 700; margin: 80px 0; text-align: center; } .container { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 40px; .article { width: 70%; } .sidebar { width: 25%; } } .content { padding: 40px 20px; border: 1px solid red; text-align: center; margin-bottom: 40px; img { width: 60%; } p { margin-top: 20px; } } .sidebar p { font-size: 20px; text-align: center; padding: 0 0 100px; &.current { color: red; } } .footer { height: 1000px; background: rgb(251, 184, 184); display: flex; justify-content: center; align-items: center; } .sidebar { position: sticky; top: 40px; } // ==================== // 今回の内容 // ==================== .sidebar-item.current { color: red; }
jQueryの記述
jQuery(function($){ //ページの読み込みが完了した後に実行されるコードを定義 $(document).ready(function() { //各種変数を格納 var content = $('.content'); var sidebar = $('.sidebar-item'); $(window).on('scroll', function () { //現在のスクロール位置を取得 var currentTop = $(window).scrollTop(); //各コンテンツに対して、以下の関数を繰り返し実行 content.each(function () { //処理中のコンテンツのdata属性の値を取得 var contentData = $(this).attr('data'); var currentSidebar = sidebar.filter('[data="' + contentData + '"]'); //処理中のコンテンツの上端と下端の情報を取得 var contentTop = $(this).offset().top; var contentBottom = $(this).height() + contentTop; //スクロール位置が処理中のコンテンツの範囲内にある場合 if( contentTop <= currentTop && currentTop < contentBottom ) { sidebar.removeClass('current'); currentSidebar.addClass('current'); } }); }); }); });
もし良かったら下記も参考にしてください
※学習中の時にまとめたものです。
解説で使用したスニペット
javascript.json
"scroll": { "prefix": "scroll", "body": [ "\\$(window).on('scroll', function () {", " $2", "});", ], "description": "scroll関数" }, "scrollTop": { "prefix": "scrollTop", "body": [ "\\$(window).scrollTop();", ], "description": "現在のスクロール位置を取得" }, "each": { "prefix": "each", "body": [ "$1.each(function () {", " $2", "});", ], "description": "each関数" },