Why write this article
I recently received a request to display and delete a floating delete button by long pressing a certain label. This requirement is actually very common on apps, but in mobile h5, we don’t have a long press event, so we need to simulate this event ourselves.
The approximate effect is as follows:
ps: In order to make a gif, I downloaded the app and had to send it to the computer via email. My head hurts. .
IdeasFrom this we can implement simulated long press events.
Up code 请把重点放在JS上,这里贴出来完整的代码是为了方便大家看个仔细,代码可以拷贝直接看效果
Most of the css is just to beautify the style, and initially hide the delete button.
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>Long press me</div> <div class=delete_btn>Delete</div> </div> <script src= ./longpress.js></script></body></html>
JS
let timer = nulllet 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) { // Handle click events 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 and touchend are only useful on mobile devices. If you want to see code examples, please:
That is, click on the image below:
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.