【Html】JS实现左滑删除功能及注意要点

3 篇文章 1 订阅

实现思路:
使用touchstart事件与touchmove事件获取到的位置做判断,从而知道是左滑还是右滑,左滑则显示删除按钮,右滑则隐藏。具体代码看下面~

touchstart事件:当手指触摸屏幕时候触发,即使已经有一个手指放在屏幕上也会触发。
touchmove事件:当手指在屏幕上滑动的时候连续地触发。在这个事件发生期间,调用preventDefault()事件可以阻止滚动。

Html:

<div class="item">
     <div class="item-box">
          <div class="column" style="flex:6;">@item</div>
          <div class="column" style="flex:4;">上架</div>
     </div>
     <div class="item-del">删除</div>
</div>

Js:

    var moveStartX, moveEndX, differX;
    // 开始触碰
    $(".item-box").on("touchstart", function (e) {
         moveStartX = e.originalEvent.changedTouches[0].pageX;
    });
    
    // 滑动
    $(".item-box").on("touchmove", function (e) {
         moveEndX = e.originalEvent.changedTouches[0].pageX,
         differX = moveEndX - moveStartX;
         // 通过开始和结束的差判断是左滑还是右滑
         if (differX > 50) {//右滑
               $(this).css('margin-left', '0');
               $('.item-del').css('display', 'none');
         } else if (differX < -50) {//左滑
               $(".item-box").css('margin-left', '0');
               $(this).css('margin-left', '-60px');
               $(this).next('.item-del').css('display', 'flex');
         }
    });

Css:

       .item {
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f5f5f5;
            margin: 20px 0;
            padding: 0 16px;
            overflow: hidden;
        }
        .item .item-box {
            display: flex;
            flex: 1;
        }
        .item .item-box .column {
            height: 46px;
            line-height: 46px;
            background-color: #f5f5f5;
            font-size: 17px;
            font-weight: bold;
        }
        .item .item-box div:nth-child(2) {
            color: #04ADBF;
            text-align: center;
        }
        .item .item-del {
            display: none;
            justify-content: center;
            align-items: center;
            width: 76px;
            height: 40px;
            text-align: center;
            background-color: #FBE8E8;
            color: #F23D3D;
            border: 2px solid #F23D3D;
            font-size: 17px;
            border-radius: 6px;
            box-sizing: border-box;
            margin-left: 8px;
        }

到这里左滑删除功能就实现啦~

注意要点:
1、开始与结束的差值differX 不能设置为大于0或者小于0;原因有二:一、这样稍微触碰到item就会左滑或者右滑,体验不好;二、上下滑动列表时也是会触碰到item;
2、不能在方法中加e.preventDefault();来阻止事件冒泡,因为加上该属性会使列表不能上下正常滚动,达不到需求;

解决方案:
1、differX设置大于50或者小于-50(具体差值根据自己需求设置即可),让它有个滑动过程再去显示或者隐藏删除按钮,体验完美;

效果演示:
在这里插入图片描述

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值