【コピペで30秒!!】超簡単!マウスでフリックをレスポンシブ対応でお手軽実装!

マウスでフリックをしたい!

マウスでのフリックはライブラリを使用したりとか、ちょっと難しい部分もあるので敬遠しがちですが、

html css jsの3ファイルにコピペするだけで簡単に実装できます。

まずはhtmlファイルからですが、構成は上記のようになるので使う要素は2つだけです。

下記をhtml css jsファイルにコピペで実装可能

htmlファイル

<div class="wrap">
	<div class="inner">
		ここにスクロールとフリックの対象となるコンテンツ内容
	</div>
</div>

cssファイル

.wrap{
  overflow: scroll;
  position: relative;
}
.inner{
  position: absolute;
  left:0;
  top:0;
}

スクロールに関してはcssで制御できるのでoverflow:scroll;でスクロール実装しましょう。

.innerの横幅を指定することで.wrapからはみ出た部分をスクロールできます。

あとは問題のフリックです。特に難しいことは考えずコピペして下さい。

jsファイルにコピペ

$(document).ready(function () {
    var divheight = $(".inner").height();
    $(".wrap").css('height',divheight);
});
$(window).resize(function () {  
    var divheight = $(".inner").height();
    $(".wrap").css('height',divheight);
});

$('.inner').on({
    'touchstart': function(e) {
        this.touchX = event.changedTouches[0].pageX;
        this.slideX = $(this).position().left;
    },
    'touchmove': function(e) {
        e.preventDefault();
        this.slideX = this.slideX - (this.touchX - event.changedTouches[0].pageX );
        $(this).css({left:this.slideX});
        this.accel = (event.changedTouches[0].pageX - this.touchX) * 5;
        this.touchX = event.changedTouches[0].pageX;
    },
        'touchend': function(e) {
        var tablewidth = $(".wrap").width();
        var tableinner = $(".inner").width();
        table_wrap_width = tableinner - tablewidth;
        this.slideX += this.accel
        $(this).animate({left : this.slideX },200,'linear');
        this.accel = 0;
        if (this.slideX > 0) {
           this.slideX = 0;
           $(this).animate({left:"0px"},500);
        }
        if (this.slideX < -table_wrap_width) {
           this.slideX = -table_wrap_width;
           $(this).animate({left:-table_wrap_width},500);
        }
    }
  });

  $('.inner').mousedown(function(e){
        this.touchX = event.pageX;
        this.slideX = $(this).position().left;

        $('.inner').mousemove(function(e){
          e.preventDefault();
          this.slideX = this.slideX - (this.touchX - event.pageX );
          $(this).css({left:this.slideX});
          this.accel = (event.pageX - this.touchX) * 5;
          this.touchX = event.pageX;
        });

  }).mouseup(function(e){
    var tablewidth = $(".wrap").width();
    var tableinner = $(".inner").width();
        table_wrap_width = tableinner - tablewidth;
        this.slideX += this.accel
        $(this).animate({left : this.slideX },200,'linear');
        this.accel = 0;
        if (this.slideX > 0) {
           this.slideX = 0;
           $(this).animate({left:"0px"},500);
        }
        if (this.slideX < -table_wrap_width) {
           this.slideX = -table_wrap_width;
           $(this).animate({left:-table_wrap_width},500);
        }
        $('.inner').off("mousemove");
  });

これでマウスでのフリックが可能になります。

ぜひ試してみて下さい。

最新情報をチェックしよう!