为啥写这篇文章
近来接了个需求,请求长按某个标签显现删除一个悬浮的删除按钮。这个需求其实在app上很罕见,但是在挪动端h5中,我们没有长按的事宜,所以就须要本身模仿这个事宜了。
也许结果以下:
思绪
摒弃click事宜,经由过程推断按的时长来决定是单击照样长按
运用touchstart和touchend事宜
在touchstart中开启一个定时器,比如在700ms后显现一个长按菜单
在touchend中消灭这个定时器,如许假如按下的时候凌驾700ms,那末长按菜单已显现出来了,消灭定时器不会有任何影响;假如按下的时候小于700ms,那末touchstart中的长按菜单还没来得及显现出来,就被消灭了。
由此我们能够完成模仿的长按事宜了。
上代码
请把重点放在JS上,这里贴出来完全的代码是为了轻易人人看个细致,代码能够拷贝直接看结果
css中大部份只是做了款式的美化,另有一开始让删除按钮隐蔽起来
HTML:
<!DOCTYPE html> <html> <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> <div id="label">长按我</div> <div>删除</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只要在挪动端装备上才有效,假如要看代码示例的话请:
用chrome
F12翻开调时窗
切换到模仿挪动装备
即点击以下图:
以上就是挪动端HTML5模仿长按删除事宜(附代码)的细致内容,更多请关注ki4网别的相干文章!