本篇文章為大家展示了怎么在html5中模擬長按事件,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
思路
放棄click事件,通過判斷按的時長來決定是單擊還是長按
使用touchstart和touchend事件
在touchstart中開啟一個定時器,比如在700ms后顯示一個長按菜單
在touchend中清除這個定時器,這樣如果按下的時間超過700ms,那么長按菜單已經(jīng)顯示出來了,清除定時器不會有任何影響;如果按下的時間小于700ms,那么touchstart中的長按菜單還沒來得及顯示出來,就被清除了。
由此我們可以實現(xiàn)模擬的長按事件了。
上代碼
請把重點放在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只有在移動端設(shè)備上才有用,如果要看代碼示例的話請:
用chrome
F12打開調(diào)時窗
切換到模擬移動設(shè)備
即點擊如下圖:
上述內(nèi)容就是怎么在html5中模擬長按事件,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
網(wǎng)站欄目:怎么在html5中模擬長按事件-創(chuàng)新互聯(lián)
分享URL:http://jinyejixie.com/article4/dcjhoe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供電子商務(wù)、響應(yīng)式網(wǎng)站、做網(wǎng)站、網(wǎng)站維護、網(wǎng)站收錄、企業(yè)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容