JavaScript實(shí)現(xiàn)點(diǎn)擊自制菜單效果
本文實(shí)例為大家分享了JavaScript實(shí)現(xiàn)點(diǎn)擊自制菜單效果的具體代碼,供大家參考,具體內(nèi)容如下
應(yīng)用場(chǎng)景:當(dāng)我們希望用戶再點(diǎn)擊右鍵的時(shí)候不希望彈出瀏覽器的默認(rèn)菜單時(shí),需要阻止瀏覽器默認(rèn)行為,并執(zhí)行我們想要的效果
第一種方式,通過(guò)創(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>
第二種:通過(guò)隱藏元素的方式
<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)擊右鍵時(shí)就不會(huì)彈出默認(rèn)的菜單了,彈出了我設(shè)置的紅框框。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. javascript xml xsl取值及數(shù)據(jù)修改第1/2頁(yè)2. 利用CSS制作3D動(dòng)畫3. Properties 持久的屬性集的實(shí)例詳解4. jsp文件下載功能實(shí)現(xiàn)代碼5. XML入門的常見(jiàn)問(wèn)題(四)6. WML語(yǔ)言的基本情況7. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究8. ASP基礎(chǔ)入門第八篇(ASP內(nèi)建對(duì)象Application和Session)9. HTML5 Canvas繪制圖形從入門到精通10. CSS代碼檢查工具stylelint的使用方法詳解
