touchend与滚动事件冲突的问题

问题描述:
content高度固定, 期中有多个p标签, 致使出现滚动.
需求是点(touchend)p标签的时候,做业务处理.
然后问题就出现了:
滚动的时候也会触发touchend.
代码示意如下:

<div id="content">
  <p>内容</p>
  <p>内容</p>
  <p>内容</p>
  ...
</div>
<script type="text/javascript">
  $(function() {
    $('#content').on('touchend', 'p', function(e) {
      console.log('touchend', +new Date);
    });
  });
</script>

效果如下图:
这里写图片描述

问题就在于如何在touchmove结束后不触发touchend.

解决方案(html不变),
touchmove时, 设置标志, 然后在touchstart时清除标志,
然后在touchend中判断, 如果有标志就不做处理(touchmove造成的), 否则再做处理:

$(function() {
  var isMoving = false;

  $('#content').on('touchend', 'p', function(e) {
    if (isMoving) {
      return;
    }

    console.log('touchend', +new Date);
  })

  .on('touchstart', 'p', function(e) {
    isMoving = false;
  })

  .on('touchmove', 'p', function(e) {
    isMoving = true;
  });
});

效果如下图:
这里写图片描述

完整测试代码如下:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta  name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
<title>touchmove scroll test page</title>
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<style type="text/css">
  * {
    margin: 0;
    padding: 0;
  }
  html, body, #content {
    height: 100%;
  }

  p {
    border: 1px solid red;
    line-height: 100px;
    text-align: center;
  }

  p:active {
    background-color: #ccc;
  }
</style>
</head>

<body>
    <div id="content">
      <p>内容</p>
      <p>内容</p>
      <p>内容</p>
      <p>内容</p>
      <p>内容</p>
      <p>内容</p>
      <p>内容</p>
      <p>内容</p>
    </div>
<script type="text/javascript">
  $(function() {
    var isMoving = false;

    $('#content').on('touchend', 'p', function(e) {
      if (isMoving) {
        return;
      }

      console.log('touchend', +new Date);
    })

    .on('touchstart', 'p', function(e) {
      isMoving = false;
    })

    .on('touchmove', 'p', function(e) {
      isMoving = true;
    });
  });

  // $(function() {
  //   $('#content').on('touchend', 'p', function(e) {
  //     console.log('touchend', +new Date);
  //   });
  // });
</script>
</body>

</html>

参考:
http://interjc.net/i/1550

欢迎补充指正!

猜你喜欢

转载自blog.csdn.net/butterfly5211314/article/details/80109145
今日推荐