エリアの動き
-スクロールすると紙芝居風に展開-

デモページを見る

See the Pen 6-5 スクロールすると紙芝居風に展開 by 動くWebデザインアイディア帳 (@ugokuweb) on CodePen.

「Result」内の表示を確かめてね!
※768px以下のウィンドウサイズだと紙芝居風にならず縦並びに表示されます。紙芝居表示は、横幅768px以上の画面でご確認ください↑

動きを実現する仕組み

CSSの position: sticky;を使用してスクロールをしたエリアを重ねて表示し、紙芝居風に見せる。
position: sticky;に対応していないブラウザにはstickyfill.jsを読み込んで対応。
※IE11は挙動が安定しない場合があります。

[使用するライブラリ]
*jQuery
*stickyfill.js(https://github.com/wilddeer/stickyfill) 

HTMLの書き方

  1. head終了タグ直前に自作のCSSを読み込みます。
    <link rel="stylesheet" type="text/css" href="css/6-5.css">
    </head>
  2. body内にHTMLを記載します。
    <header id="header">
    <h1>Logo</h1>
    </header>
    
    <main id="container">
    
    <section class="fixed">
    <h2>Area 1</h2>
    <!--/area1--></section>
    
    <section class="fixed">
    <h2>Area 2</h2>
    <!--/area2--></section>
    
    <section class="fixed">
    <h2>Area 3</h2>
    <!--/area3--></section>
    
    <!--/main--></main>
    
    <footer id="footer">
    <small>&copy; copyright.</small>
    </footer>
  3. body 終了タグ直前に jQuery、stickyfill.jsと、動きを制御する自作のJS の3 つを読み込みます。
    <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stickyfill/2.1.0/stickyfill.min.js"></script>
    <!--自作のJS-->
    <script src="js/6-5.js"></script>
    </body>

自作のCSS内の書き方

#header{
	position: fixed;/*Header固定*/
	top:0;
	height: 70px;/*高さ指定*/
	z-index: 2;
	width:100%;
	background:#fff;/*背景色*/
}

#container{
	position: relative;
	z-index: 1;/*header とfooterを手前にするため数字を小さく*/
}

section.fixed{
	position: -webkit-sticky;/*Safari*/
	position: sticky;
	top:70px;/*Header高さ分で止まるようにする*/
	padding: 600px 0;/*デモ画面の高さを持たすための上下余白*/
}

section.fixed:nth-child(odd){
   background:#666;/*デモ画面の奇数背景色*/
}

section.fixed:nth-child(even){
   background:#333;/*デモ画面の偶数背景色*/
}

section.fixed:last-of-type{
	padding-top:70px;
/*最後のセクションだけ止まらないため、エリア内の情報が少ない時は、Header分の高さをpadding-topに追加して上部が見えるようにする*/
}
#footer{
	position: relative;
	z-index: 2;
}

/*=====タブレット以下の見え方 =====*/

@media screen and (max-width:768px){
	section.fixed{
	position:relative!important;/*sticky解除*/
	top:0;/*70px⇒0pxに戻す*/
}
	section.fixed:first-of-type{
	padding-top:100px;
	/*最初の要素は上部にHeaderの高さ以上の余白をとる*/
	}
}

自作のJS内の書き方

768px以下では紙芝居風を解除するため、position: sticky;に対応していないブラウザ対応用のJavaScriptを、768pxより大きい場合に読み込む。

$(window).on('load resize', function() {
var windowWidth = window.innerWidth;
var elements = $('.fixed');
if (windowWidth >= 768) {
Stickyfill.add(elements);
}else{
Stickyfill.remove(elements);
} 
});

この技術を使ったサンプルサイト

バリエーション
を見る

「印象」に関わる
動き一覧

書籍情報

紙面だからこそできるまとめ方でコードを説明し、
全体を俯瞰して調べることが出来る構成になっています。

もちろん、パーツのサンプルコードもzipでまとめてダウンロードできます。
購入をしてくださった方には特典がありますので是非チェックしてみてください!

書籍紙面サンプル

出版社:ソシム株式会社
2021/2/27 発売

書籍紙面サンプル

出版社:ソシム株式会社
2021/7/31 発売

Page
Top