自訂右鍵選單
自訂右鍵選單,對於某些ERP系統,功能操作比較多,所以我們通常把常用的幾個功能放在自訂的右鍵選單裡方便使用者使用。
實作自訂選單很簡單,首先我們要屏蔽原始的右鍵選單,自訂選單出現在滑鼠的位置,點擊隱藏自訂選單,過程就是這樣的。
*{margin:0;padding:0} a{text-decoration:none} ul li{list-style:none} .menu{border:1px solid black;border-radius:5px;display:inline-block;position:fixed;top:100px;left:550px; overflow:hidden;padding-bottom:10px;box-shadow:0 0 10px 0;z-index:999;display:none;background:white} .menu ul li{height:30px;width:100%} .menu ul li a{height:30px;display:inline-block;width:100%;text-align:left;line-height:30px;padding:5px 10px} .menu li a:hover{background-color:#EEF5E2}
<div class="menu" id="demo"> <ul> <li><a href="#">向录入员发送消息</a></li> <li><a href="#">发送选中作业</a></li> <li><a href="#">设置作业状态</a></li> <li><a href="#">哈哈哈哈哈</a></li> <li><a href="#">嘻嘻嘻嘻嘻</a></li> <li><a href="#">呵呵呵呵呵呵</a></li> </ul> </div>
1.屏蔽原始的右鍵選單
在JS中提供了一個事件來完成這件事就是oncontextmenu,這個是事件綁定的區域在點擊右鍵時將不會再出現原始右鍵選單:
document.oncontextmenu = function(){ return false; }
function getHideDOMWH(obj){ //obj为菜单元素的DOM对象 var wh = {}; obj.style.visibility = "hidden"; wh.w = obj.scrollWidth; wh.h = obj.scrollHeight; obj.style.visibility = null; return wh; }
document.onmousedown = function(e){ //obj为菜单元素DOM对象 var e = e || window.event; if(e.button==2){ var left = e.clientX; var top = e.clientY; var windowHeight = document.body.scrollHeight; var windowWidth = document.body.scrollWidth; var wh = getHideDOMWH(obj); var contentHeight = wh.h; var contentWidth = wh.w; obj.style.left = windowWidth-left>contentWidth?left+"px":windowWidth-contentWidth+"px"; obj.style.top = windowHeight-top>contentHeight?top+"px":top-contentHeight+"px"; obj.style.display = "inline-block"; } }
document.onclick = function(){ //obj为菜单元素DOM对象 obj.style.display = "none"; }
function contextMenu(obj){ //obj为DOM对象 document.oncontextmenu = function(){ return false; } document.onmousedown = function(e){ var e = e||window.event; if(e.button==2){ var mouseX = e.clientX; var mouseY = e.clientY; var wh = getObjWH(obj); var contentW = wh.w; var contentH = wh.h; var documentW = document.body.scrollWidth; var documentH = document.body.scrollHeight; obj.style.left = documentW-mouseX<contentW?documentW-contentW+"px":mouseX+"px"; obj.style.top = documentH-mouseY<contentH?mouseY-contentH+"px":mouseY+"px"; obj.style.display = "inline-block"; } } document.onclick = function(){ obj.style.display = "none"; } function getObjWH(obj){ var wh = {}; obj.style.visibility = "hidden"; wh.w = obj.scrollWidth; wh.h = obj.scrollHeight; obj.style.visibility = null; return wh; } }