JavaScript實(shí)現(xiàn)點(diǎn)擊自制菜單效果
本文實(shí)例為大家分享了JavaScript實(shí)現(xiàn)點(diǎn)擊自制菜單效果的具體代碼,供大家參考,具體內(nèi)容如下
應(yīng)用場景:當(dāng)我們希望用戶再點(diǎn)擊右鍵的時候不希望彈出瀏覽器的默認(rèn)菜單時,需要阻止瀏覽器默認(rèn)行為,并執(zhí)行我們想要的效果
第一種方式,通過創(chuàng)建元素的方式
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <title>Document</title> <style> body { height: 3000px; }.menu { width: 100px; height: 280px; background-color: red; position: absolute; left: 0; top: 0; display: none; } </style></head><body> <script> var Bon = true; var menu = null; document.oncontextmenu = function(event) { if (Bon) {menu = document.createElement('div');menu.classList.add('menu');document.body.appendChild(menu);menu.style.left = event.pageX + 'px';menu.style.top = event.pageY + 'px';menu.style.display = 'block';Bon = false;event.preventDefault(); } else {menu.style.left = event.pageX + 'px';menu.style.top = event.pageY + 'px';event.preventDefault(); } } document.onmousedown = function(e) { if (e.button == 0) {var menu = document.querySelector('.menu');document.body.removeChild(menu);Bon = true; } } </script></body></html>
第二種:通過隱藏元素的方式
<div class='menu'></div> <script> var menu = document.querySelector('.menu'); document.oncontextmenu = function(event) { menu.style.left = event.pageX + 'px'; menu.style.top = event.pageY + 'px'; menu.style.display = 'block'; event.preventDefault(); } document.onmousedown = function(e) { if (e.button == 0) {menu.style.display = 'none'; } }</script>
當(dāng)我們點(diǎn)擊右鍵時就不會彈出默認(rèn)的菜單了,彈出了我設(shè)置的紅框框。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python如何批量生成和調(diào)用變量2. python利用opencv實(shí)現(xiàn)顏色檢測3. windows服務(wù)器使用IIS時thinkphp搜索中文無效問題4. ASP.NET MVC實(shí)現(xiàn)橫向展示購物車5. Python基于requests實(shí)現(xiàn)模擬上傳文件6. Python sorted排序方法如何實(shí)現(xiàn)7. Python 中如何使用 virtualenv 管理虛擬環(huán)境8. ASP.Net Core(C#)創(chuàng)建Web站點(diǎn)的實(shí)現(xiàn)9. Python獲取B站粉絲數(shù)的示例代碼10. 通過CSS數(shù)學(xué)函數(shù)實(shí)現(xiàn)動畫特效
