LoginSignup
0
0

【jQuery】PC時のタップ・スワイプ処理の実装

Last updated at Posted at 2023-12-29

html css

<div id="wrap">
  <div class="box">スワイプ削除</div>
</div>
<style>
#wrap {
    position: relative;
    width: 100%;
    max-width: 318px;
}
.box {
    position: absolute;
    top: 0;
    left: 0;
    width: 60px;
    background-color: #ccc; 
    cursor: grab;
    }
    
    .box:active {
        cursor: grabbing;
    }
 </style>

Jquery

$(function() {
    var swWrap = $('#wrap');
    var sw = swWrap.children('.box');
    var basePoint;
    var distanceMoved = 0; // 追加:移動距離を追跡する変数

    sw.bind({
        'mousedown': function(e) {
            e.preventDefault();
            this.pageX = e.pageX;
            basePoint = this.left = parseFloat($(this).css('left')); 
            this.touched = true;
        },
        'mousemove': function(e) {
            if(!this.touched) {
                return;
            }
            e.preventDefault();
            var moveX = this.pageX - e.pageX; // 左方向への移動を検知
            if (moveX > 0) {
                return;
            }
            this.left = parseFloat($(this).css('left')) - (this.pageX - e.pageX);
            $(this).css({
                left: this.left
            });
            this.pageX = e.pageX;
            distanceMoved += Math.abs(this.left - basePoint); // 更新:移動距離を更新
        },
        'mouseup': function(e) {
            if(!this.touched) {
                return;
            }
            this.touched = false;
            if(this.left > 0) {
                $(this).animate({
                    left: 0
                }, 200);
            } else if(this.left < swWrap.width() -  sw.width()) {    
  
                 if(distanceMoved < 10) {
                     $(this).animate({
                        left: basePoint
                    }, 200);
                } else {
                     $(this).animate({
                    		left: swWrap.width() -  sw.width()
                		}, 200);
                }
            }
            distanceMoved = 0; // リセット:次のスワイプのために移動距離をリセット
        },
        'mouseout': function(e) {
            if(!this.touched) {
                return;
            }
            this.touched = false;
            $(this).animate({
                left: basePoint
            }, 200);
            distanceMoved = 0; 
            if(Math.abs(this.left - basePoint) > swWrap.width() / 2) {
            	$('#wrap .box').remove();
     				}
        }
    });
});

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0