scrollFinishイベントの実装
フローティングメニューを実現する仕組みの一部として、画面スクロールが止まったことを検知するscrollFinishイベントを実装した。
HTML
<div class="str-container">
<div id="header" class="str-header">
<p>ヘッダー</p>
</div><!-- /.str-header -->
<div class="str-contents">
<div class="str-main">
<p>メインコンテンツ</p>
</div><!-- /.str-main -->
<div class="str-sub">
<p>サブコンテンツ</p>
</div><!-- /.str-sub -->
</div><!-- /.str-contents -->
<div class="str-footer">
<p>フッターコンテンツ</p>
</div><!-- /.str-footer -->
</div><!-- /.str-container -->
CSS
/* -----------------------------------------------------------
Skelton
----------------------------------------------------------- */
body{
background-color:#efefeb;
line-height:1.5;
font-family:"ヒラギノ角ゴ Pro W3", "Hiragino Kaku Gothic Pro", "メイリオ", "MS Pゴシック", sans-serif;
font-size:0.875em;
}
.str-container{
margin:0 auto;
padding-bottom:15px;
width:540px;
background-color:#fff;
}
.str-contents{
position:relative;
margin-bottom:20px;
}
.str-contents .str-main{
width:350px;
}
.str-contents .str-sub{
position:absolute;
top:0;
right:10px;
width:180px;
}
/* -----------------------------------------------------------
Header
----------------------------------------------------------- */
.str-header{
position:relative;
margin-bottom:30px;
border-bottom:4px solid #222;
height:40px;
}
/* -----------------------------------------------------------
Main
----------------------------------------------------------- */
.str-main{
height:3000px;
}
/* -----------------------------------------------------------
Sub
----------------------------------------------------------- */
.str-sub{
height:200px;
background-color:#efefef;
}
/* -----------------------------------------------------------
Footer
----------------------------------------------------------- */
.str-footer{
padding-top:10px;
border-top:4px solid #222;
height:50px;
}
JavaScript
$(function () {
// 変数宣言
/* var $target = $(".str-sub"), // div.str-subをフローティングメニューにする
$window = $(window),
$document = $(document),
timerId,
// function variable
defaultPos = $target.offset().top,
targetHeight = $target.outerHeight(true),
containerHeight = $target.parent().height(),
DURATION = 500; */
// フローティングメニューの実現
function floatingMenu(scrollTop) {
var setPos;
setPos = scrollTop - defaultPos + 10;
if (scrollTop <= defaultPos) {
$target.stop(true)
.animate({ top: 0 }, DURATION);
} else if (scrollTop > defaultPos && setPos + targetHeight < containerHeight) {
$target.stop(true)
.animate({ top: setPos }, DURATION);
}
}
// 要素がなければ終了
if (!$target.length) {
return;
}
// スクロール停止イベントのバインド
$window.bind("scrollFinish", function (event, scrollTop) {
// メニュー移動処理呼び出し
floatingMenu(scrollTop);
});
// スクロールイベントのバインド
$window.bind("scroll", function () {
var scrollTop = $document.scrollTop();
if (timerId) {
clearTimeout(timerId);
}
// 1秒間スクロールしない場合はscrollFinishイベントを呼び出し
timerId = setTimeout(function () {
timerId = null;
$window.trigger("scrollFinish", [scrollTop]);
}, 1000);
});
$window.unload(function () {
$window.unbind("scroll scrollFinish");
});
});