JavaScript 自定義html元素鼠標(biāo)右鍵菜單功能
自定義html元素鼠標(biāo)右鍵菜單
實(shí)現(xiàn)思路
在觸發(fā)contextmenu事件時(shí),取消默認(rèn)行為(也就是阻止瀏覽器顯示自帶的菜單),獲取右鍵事件對(duì)象,來確定鼠標(biāo)的點(diǎn)擊位置,作為顯示菜單的left和top值
編碼實(shí)現(xiàn)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> window.onload = function(){ var menu = document.getElementById('menu'); document.body.oncontextmenu = function(e){ // 自定義body元素的鼠標(biāo)事件處理函數(shù) var e = e || window.event; e.preventDefault(); //阻止系統(tǒng)右鍵菜單 IE8-不支持 // 顯示自定義的菜單調(diào)整位置 let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;// 獲取垂直滾動(dòng)條位置 let scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;// 獲取水平滾動(dòng)條位置 menu.style.display = 'block'; menu.style.left = e.clientX + scrollLeft + 'px'; menu.style.top = e.clientY + scrollTop + 'px'; } // 鼠標(biāo)點(diǎn)擊其他位置時(shí)隱藏菜單 document.onclick = function(){ menu.style.display = 'none'; } } </script> <style> *{ margin: 0; padding: 0; } p{ margin-top: 200px; } ul li{ list-style-type: none; margin: 10px 0; text-align: center; } #menu{ border:1px solid #ccc; background: #eee; position: absolute; // 設(shè)置菜單為絕對(duì)位置 width: 100px; height: 120px; display: none; } </style> </head> <body style="overflow:auto"> <div id="box" style="height:5000px; width:5000px">讓body元素出現(xiàn)滾動(dòng)條用的div</div> <div id="menu"> <ul> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" >分享</a></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" >收藏</a></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" >舉報(bào)</a></li> </ul> </div> </body> </html>
實(shí)現(xiàn)效果
總結(jié)
以上所述是小編給大家介紹的JavaScript 自定義html元素鼠標(biāo)右鍵菜單功能,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
- javascript局部自定義鼠標(biāo)右鍵菜單
- JavaScript模擬鼠標(biāo)右鍵菜單效果
- javascript鼠標(biāo)右鍵菜單自定義效果
- js實(shí)現(xiàn)完全自定義可帶多級(jí)目錄的網(wǎng)頁鼠標(biāo)右鍵菜單方法
- 深入探討JavaScript、JQuery屏蔽網(wǎng)頁鼠標(biāo)右鍵菜單及禁止選擇復(fù)制
- js捕獲鼠標(biāo)右鍵菜單中的粘帖事件實(shí)現(xiàn)代碼
- JavaScript 對(duì)任意元素,自定義右鍵菜單的實(shí)現(xiàn)方法
- JS簡(jiǎn)單實(shí)現(xiàn)自定義右鍵菜單實(shí)例
- javascript全局自定義鼠標(biāo)右鍵菜單
相關(guān)文章
Three.js 再探 - 寫一個(gè)微信跳一跳極簡(jiǎn)版游戲
最近項(xiàng)目結(jié)束,很空閑,于是就試著仿照微信跳一跳寫了一個(gè)極簡(jiǎn)版的游戲,到底簡(jiǎn)單到什么程度呢?大家可以參考下本文2018-01-01JavaScript?對(duì)象新增方法defineProperty與keys的使用說明
這篇文章主要介紹了JavaScript對(duì)象新增方法defineProperty與keys的使用說明,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-09-09js獲取客戶端外網(wǎng)ip的簡(jiǎn)單實(shí)例
這篇文章主要介紹了js獲取客戶端外網(wǎng)ip的簡(jiǎn)單實(shí)例,有需要的朋友可以參考一下2013-11-11javascript高亮效果的二種實(shí)現(xiàn)方法
js高亮效果實(shí)現(xiàn)代碼,直接靜態(tài)頁面即可,不用每次都要生成2008-09-09