Open1

JavaScriptでフリック検知

としひでとしひで

フリックを検知する

HTML
<div class="box" ontouchstart="flickStart(event)" ontouchmove="flicking(event)" ontouchend="flickEnd(event)"></div>
<div class="box" ontouchstart="flickStart(event)" ontouchmove="flicking(event)" ontouchend="flickEnd(event)"></div>
<div class="box" ontouchstart="flickStart(event)" ontouchmove="flicking(event)" ontouchend="flickEnd(event)"></div>
CSS
.box{
  width:20vw;
  height:20vh;
  border-radius:12px;
  background-color:#fff;
  transition: all 100ms ease;
}
.leftswipe{
    transform: translateX(-6rem);
    transition: all 500ms ease;
}
JS
function flickStart(event){
    event.preventDefault();
	startX = event.touches[0].pageX;
} 
function flicking(event){
    event.preventDefault();
	endX = event.touches[0].pageX;
}
function flickEnd(event){
    if( (endX - startX) < 0 ) {//左スワイプ
        
        event.classList.add("leftswipe");

    } else {//右スワイプ
        event.classList.remove("leftswipe");
 
    }
}

サンプル

左にフリックしてください(モバイル)

ログインするとコメントできます