怎么在html5中模拟长按事件

发布时间:2021-05-18 16:30:05 作者:Leah
来源:亿速云 阅读:244

本篇文章为大家展示了怎么在html5中模拟长按事件,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

思路

由此我们可以实现模拟的长按事件了。

上代码

请把重点放在JS上,这里贴出来完整的代码是为了方便大家看个仔细,代码可以拷贝直接看效果
css中大部分只是做了样式的美化,还有一开始让删除按钮隐藏起来

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="./longpress.css" />
</head>
<body>
    <div class="container">
        <div class="label" id="label">长按我</div>
        <div class="delete_btn">删除</div>
    </div>
    <script src="./longpress.js"></script>
</body>
</html>

JS

let timer = null
let startTime = ''
let endTime = ''
const label = document.querySelector('.label')
const deleteBtn = document.querySelector('.delete_btn')

label.addEventListener('touchstart', function () {
  startTime = +new Date()
  timer = setTimeout(function () {
    deleteBtn.style.display = 'block'
  }, 700)
})

label.addEventListener('touchend', function () {
  endTime = +new Date()
  clearTimeout(timer)
  if (endTime - startTime < 700) {
    // 处理点击事件
    label.classList.add('selected')
  }
})

CSS

.container {
    position: relative;
    display: inline-block;
    margin-top: 50px;
}

.label {
    display: inline-block;
    box-sizing: border-box;
    width: 105px;
    height: 32px;
    line-height: 32px;
    background-color: #F2F2F2;
    color: #5F5F5F;
    text-align: center;
    border-radius: 3px;
    font-size: 14px;
}

.label.selected {
    background-color: #4180cc;
    color: white;
}

.delete_btn {
    display: none;
    position: absolute;
    top: -8px;
    left: 50%;
    transform: translateX(-50%) translateY(-100%);
    color: white;
    padding: 10px 16px;
    background-color: rgba(0, 0, 0, .7);
    border-radius: 6px;
    line-height: 1;
    white-space: nowrap;
    font-size: 12px;
}

.delete_btn::after {
    content: '';
    width: 0;
    height: 0;
    border-width: 5px;
    border-style: solid;
    border-color: rgba(0, 0, 0, .7) transparent transparent transparent;
    position: absolute;
    bottom: -9px;
    left: 50%;
    transform: translateX(-50%);
}

ps: touchstart和touchend只有在移动端设备上才有用,如果要看代码示例的话请:

  1. 用chrome

  2. F12打开调时窗

  3. 切换到模拟移动设备

即点击如下图:

怎么在html5中模拟长按事件

上述内容就是怎么在html5中模拟长按事件,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. OnLongClickListener长按事件设置墙纸
  2. uitableviewcell 的长按事件

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

html5

上一篇:怎么在htnl5中利用svg实现页面高斯模糊

下一篇:Linux中有哪些常用的ctrl组合键

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》