最近看js高級程式設計的時候突然看到了contextmenu屬性,之前在做專案的時候也遇到過,用來阻止滑鼠右鍵彈出,(ps:禁止別人複製),今天突然想了一下試著用這個屬性來實現以下右鍵選單效果。
<!DOCTYPE html><html lang="en"><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"> <link rel="stylesheet" href="css/page/index.css"> <title>javascript实现右键菜单效果</title> <style> *{padding:0;margin:0;} .menu{display:none;position:fixed;width:125px;} .menu ul li{ height:30px; width:120px; margin-top:-1px ; line-height:30px; border:1px solid #eee; text-align:center; list-style:none; } .menu ul li:hover{ background:#ccc; cursor:default; user-select: none; } </style></head><body> <p class="menu"> <ul> <li>导航菜单1</li> <li>导航菜单2</li> <li>导航菜单3</li> <li>导航菜单4</li> </ul> </p></body></html><script> function $(selector){ return document.querySelectorAll(selector); } var li = $(".menu ul li"); var menu = $(".menu")[0]; //右键菜单单击 document.oncontextmenu = function(event){ var ev = event || window.event; var mX = event.clientX; var mY = event.clientY; menu.style.display = "block"; menu.style.left = mX + "px"; menu.style.top = mY + "px"; return false; //取消window自带的菜单弹出来 } //点击页面菜单消失 document.onclick = function(){ menu.style.display = "none"; } //阻止点击li冒泡 for(var i = 0, len = li.length; i < len; i++ ){ li.item(i).onclick = function(event){ var ev = event || window.event; console.log(this.innerText); if(ev.stopPropagation()){ ev.stopPropagation(); }else{ ev.cancelBubble = false; } } }</script>
相關推薦:
以上是javascript實作右鍵選單效果方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!