jQueryでスライダーをスワイプ

2012年8月24日 金曜日

jQueryプラグインで実装できるスライダーにスワイプ機能(スマホ対応)の追加をしました。

利用したのは下記プラグイン
jQuery Slider2
スライダー機能を実装します。実際動いているスライダー内の download ボタンからダウンロード。
TouchSwipe
スワイプ機能の実装。Latest TouchSwipe on github download からダウンロード。

【html header】
jquery本体と、DLした3つのcssとjsを読み込みます。

<link rel="stylesheet" href="jquery.slider.css">
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="jquery.slider.min.js"></script>
<script type="text/javascript" src="jquery.touchSwipe.min.js"></script>

jQuery Sliderの設定

<script type="text/javascript">
$(function(){
	$('#slideArea').slider({     //コンテンツを内包する要素の設定
		autoplay: true,      //自動再生
		showPosition: true,  //現在の表示
		hoverPause: true,    //マウスオーバーで停止
		wait: 3000,          //停止時間
		fade: 500,           //スライド時間
		direction: "left"    //スライド方向
	});
});
</script>

【javascript】
ここで、スワイプするとスライダーが動くように先ほど読み込んだ jquery.slider.min.js に記述を追加します。
インデントが削除してあって見づらいですが、コード最後のほうにある ”_init();” で改行して下記4行を記述します。

~~~~_init();
//スワイプ用ここから
$(this).swipe({
	swipeLeft:function(eventfingerCount){_next();},  //左にスワイプ
	swipeRight:function(eventfingerCount){_prev();}  //右にスワイプ
});
//スワイプ用ここまで
};})(jQuery);

【html body】
slideAreaを設定した中にコンテンツを記述します。

<div id="slideArea">
	<div class="item">
		<h3 class="title">SLIDE1</h3>
		<div><img src="image1.jpg"></div>
	</div>
	<div class="item">
		<h3 class="title">SLIDE2</h3>
		<div><img src="image2.jpg"></div>
	</div>
	<div class="item">
		<h3 class="title">SLIDE3</h3>
		<div><img src="image3.jpg"></div>
	</div>
</div>

これで、PCでもスマホでもスワイプしてスライダーの制御ができます。

→DEMO

下記サイト様のサンプル等を参考にさせて頂きました。
JavaScriptでdiv要素をさくっとスライド!「jQuery Slider2」
「TouchSwipe」スワイプイベント実装用のjQueryプラグイン

(Visited 2,803 times, 1 visits today)

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

トラックバック

 トラックバックURL
http://lettuce-eater.com/blog/archives/147/trackback