現状・目標
シンプルに下ボタンを押せば下に、上ボタンを押せば上に
指定したクラスに一個ずつスクロールするjsを組みたいです。
参考URLを参考に作りました。
これの、逆をやりたいです。
問題点
上ボタンを押下したら、-2するようしましたが、
現在の問題点が、画面TOPから中途半端な部分に
セクションがある場合、上ボタンを押しても2つ前要素のsectionに移動してしまいます。
一番下に持って行った時の動きがわかりやすいかと思います。
###DEMO
かと言って-1に値を変えれば、次のsectionに移動してくれません。
sectionが中途半端な位置にある場合や、一番最後のsectionに到達した時に1つ戻る方法
はどのように記述すればよろしいでしょうか。
お力を貸していただけると嬉しいです。
ソースコード
HTML
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="gridContainer clearfix"> <div id="next_btn">↓</div> <div id="back_btn">↑</div> <div class="section1 cor1 control"></div> <div class="section2 cor2 control"></div> <div class="section3 cor3 control"></div> <div class="section4 cor1 control"></div> <div class="section5 cor2 control"></div> <footer class="control">footer</footer> </div>
js
$(function() { var idx = -1; var controlPos = 0; var scrollTop = 0; var targetTop = 0; $(function(){ $(window).on("load scroll", function(e){ $(".control").each(function(index, ele){ controlPos = $(ele).offset().top; scrollTop = $(window).scrollTop(); idx = -1; if(controlPos > scrollTop){ idx = index; return false; } }); }); $("#next_btn").on("click", function(e){ if($(".control").eq(idx).is("*") && idx >= 0){ idx = idx; console.log("idx:"+idx); targetTop = $(".control").eq(idx).offset().top; $("html, body").animate({scrollTop:targetTop}, "normal"); } return false; }); $("#back_btn").on("click", function(e){ if($(".control").eq(idx).is("*") && idx >= 0){ idx2 = idx-2; console.log("idx2:"+idx2); if(idx2 === -1){ return false; } targetTop = $(".control").eq(idx2).offset().top; $("html, body").animate({scrollTop:targetTop}, "normal"); } return false; }); }); });
css
#next_btn{ line-height:70px; height: 70px; width: 70px; border-radius:100%; display: inline-block; background: #4285F4; color:white; margin: 1.3%; box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12); top: 0; left:0; position: fixed; font-size:50px; text-align:center; } #back_btn{ line-height:70px; height: 70px; width: 70px; border-radius:100%; display: inline-block; background: #F44141; color:white; margin: 1.3%; box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12); top: 0; right:0; position: fixed; font-size:50px; text-align:center; } footer{ width: 100%; height: 150px; float: left; background-color: bisque; } .section1{ width: 100%; height: 150px; float: left; } .section2{ width: 100%; height: 354px; float: left; } .section3{ width: 100%; height: 441px; float: left; } .section4{ width: 100%; height: 311px; float: left; } .section5{ width: 100%; height: 810px; float: left; } .cor1{background-color: tan;} .cor2{background-color: blue;} .cor3{background-color:darkcyan;}
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/09/12 16:11
2016/09/13 06:17
2016/09/13 06:19
2016/09/13 13:32