这篇文章主要介绍了在html5中如何实现长按事件效果的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇在html5中如何实现长按事件效果文章都会有所收获,下面我们一起来看看吧。
最近接了个需求,要求长按某个标签显示删除一个悬浮的删除按钮。这个需求其实在app上很常见,但是在移动端h6中,我们没有长按的事件,所以就需要自己模拟这个事件了。
ps: 为了做个 gif 还下了 app ,还得通过邮件发到电脑上,脑瓜疼。。
思路
由此我们可以实现模拟的长按事件了。
上代码
请把重点放在JS上,这里贴出来完整的代码是为了方便大家看个仔细,代码可以拷贝直接看效果
css中大部分只是做了样式的美化,还有一开始让删除按钮隐藏起来
HTML:
Document
长按我
删除
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只有在移动端设备上才有用,如果要看代码示例的话请:
用 chrome
F12打开调时窗
切换到模拟移动设备
关于“在html5中如何实现长按事件效果”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“在html5中如何实现长按事件效果”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。