自定義鼠標右擊菜單要素:
禁止頁面默認右擊事件
設置右擊菜單的樣式以及菜單出現的位置(通過捕獲鼠標點擊位置來確定菜單的位置)
鼠標在指定控件(區域)上右擊時顯示菜單(默認菜單隱藏,點擊鼠標右鍵時顯示)
效果圖
代碼如下:
HTML代碼
!DOCTYPE html html 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= right-click.css / /head body div id= contain-friend 右擊顯示菜單 /div label id= label1 /label div id= menu-friend div button id= btn1 菜單一 /button /div div button id= btn2 菜單二 /button /div /div script src= right-click.js /script /body /html
HTML
JS代碼
關于菜單的定位主要是在第一個if語句部分,后面為驗證按鈕效果。
menu1.style.left和menu1.style.top用于對菜單進行定位,由css樣式表可知menu1的position屬性定位為absolute,style.top定位相對于離它最近的position屬性值不為static的父輩元素,此處即為body。
menu的位置需要根據頁面布局的具體情況來判斷是e.offsetX/Y、e.clientX/Y或是其它,此處加上document.documentElement.scrollTop是考慮加上滾動條的情況(實際上這個例子里面并沒有滾動條)。
window.onload = function() { //以下為自定義右擊菜單 document.oncontextmenu = function(e) { //阻止執行瀏覽器默認右擊事件 e.preventDefault(); //聊天室好友列表 if (document.getElementById( menu-friend )) { var menu1 = document.getElementById( menu-friend menu1.style.display = block document.getElementById( contain-friend ).onmousedown = function(e) { //菜單定位 menu1.style.left = e.offsetX + px menu1.style.top = document.documentElement.scrollTop + e.clientY + px //alert(menu1.style.top) if (document.getElementById( contain-friend )) { if (e.button == 2) { menu1.style.visibility = visible } else { menu1.style.visibility = hidden if (document.getElementById( btn1 )) { document.getElementById( btn1 ).onmousedown = function(e) { document.getElementById( label1 ).innerHTML = 你點擊了菜單一 if (document.getElementById( btn2 )) { document.getElementById( btn2 ).onmousedown = function(e) { document.getElementById( label1 ).innerHTML = 你點擊了菜單二 return false; //與e.preventDefault();功能相同,但是必須放在最后否則在return后面的內容均不執行}
JavaScript文件
CSSyangshi_10628_1.html' target='_blank'>CSS樣式表
1/*自定義右擊菜單*/
.contain { background-color: #D1CEBC; height: 100px; width: 300px;.menu { width: 150px; background-color: white; visibility: hidden; position: absolute; box-shadow: 0px 0px 10px #D1CEBC.menu-item { background-color: #fff; margin: 0;.menu-item-btn { width: 146px; margin: 2px; border: 0; text-align: left; padding-left: 60px; padding-top: 5px; padding-bottom: 5px; background-color: #fff; color: #000;.menu-item-btn:hover { background-color: #D1CEBC;}
相信看了這些案例你已經掌握了方法,更多精彩請關注php 其它相關文章!
相關閱讀:
HTML中關于盒模型的總結
html語義化有那些作用
HTML中移動端有哪些布局方案
input的文本框怎么做到和img驗證碼
以上就是JS如何實現自定義鼠標右擊菜單的詳細內容,html教程
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答