現在Webの勉強でスクロール量に応じて要素を拡大、縮小をしたいと考えて、調べるとこのサイトがヒットしたのでこれを参考に見ながらですが実装をしていき、スクロール量を取得する方法はわかりましたが、このサイトではboxの要素を3つ使用して実装していたので、試しに要素を一つにして実装してみるとうまく行きませんでした。
やりたいことは、要素一つだけをスクロール量に応じて拡大、縮小するということです。
html
1 2<!DOCTYPE html> 3<html> 4 <head> 5 <meta charset="utf-8"> 6 <title>サンプルサイト</title> 7 <meta name="viewport" content="width=device-width, initial-scale=1"> 8 9 <!-- Link --> 10 <link rel="stylesheet" href="../css/jquery-ui.min.css"> 11 <link rel="stylesheet" href="../css/simple.css"> 12 13 <!-- Favicon --> 14 <link rel="shortcut icon" href="http://example.com/imgs/favicon.ico"> 15 16 <!-- script --> 17 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> 18 <script src="../js/contents.js"></script> 19 <script type="text/javascript" src="//typesquare.com/3/tsst/script/ja/typesquare.js?5b0ba9a48558452fbd3351a4ac1e02ec" charset="utf-8"></script> 20 </head> 21<body> 22 23 24 25 26 27<div class="container "> 28 <div class="box1"></div> 29</div> 30<div class="container "> 31 <div class="box2"></div> 32</div> 33<div class="container "> 34 <div class="box3"></div> 35</div> 36 37 38 39</body> 40</html>
css
1 .container { 2 position: relative; 3 min-height: 100vh; 4 overflow: hidden; 5 font-size: 28px; 6 color: #444; 7 background: #fff; 8 margin-bottom: 20px; 9 box-sizing: border-box; 10 } 11 .container .box1 { 12 position: relative; 13 min-height: 100vh; 14 box-sizing: border-box; 15 text-align: left; 16 padding: 10px; 17 } 18 .container .box2 { 19 position: absolute; 20 height: 5px; 21 background: #9fb7d4; 22 width: 100%; 23 } 24 .container .box3 { 25 position: relative; 26 height: 5px; 27 background: #9fb7d4; 28 width: 100%; 29 }
javascript
1$(function () { 2 $('.container .box2').css({'right':'0','width':'0'}); 3 $('.container .box3').css({'left':'0','width':'0'}); 4 $('.container .box2,.container .box3').each(function () { 5 var winH = $(window).height(); 6 var obj = $(this); 7 var offset = obj.offset().top; 8 pos = 0, 9 $(window).scroll(function () { 10 scroll = $(window).scrollTop(); 11 pos = (1 - (offset - scroll) / winH) * 2 * 100; 12 if (scroll > offset - winH) { 13 obj.width(pos + '%'); 14 } 15 }); 16 }); 17 });
これはboxが3つあるので、このbox要素を一つにして、スクロール量に応じて拡大、縮小する機能を実装したいです。
やりたいことは単純なのですが、理解できない自分がいるのでご教授お願いいたします。
あなたの回答
tips
プレビュー