最近接了個需求,要求長按某個標籤顯示刪除一個懸浮的刪除按鈕。這個需求其實在app上很常見,可是在移動端h5中,咱們沒有長按的事件,因此就須要本身模擬這個事件了。css
大概效果以下:html
ps: 爲了作個gif還下了app,還得經過郵件發到電腦上,腦瓜疼。。chrome
由此咱們能夠實現模擬的長按事件了。app
請把重點放在JS上,這裏貼出來完整的代碼是爲了方便你們看個仔細,代碼能夠拷貝直接看效果
css中大部分只是作了樣式的美化,還有一開始讓刪除按鈕隱藏起來ui
<!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>
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') } })
.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只有在移動端設備上纔有用,若是要看代碼示例的話請:spa
即點擊以下圖:code
歡迎交流~orm