html右鍵選單實現方法
阿新 • • 發佈:2021-01-09
引用jquery
HTML
<div id="sub-menu"> <table cellspace="3"> <tr> <td> <input type="button" class="sub-menu-btn" name="" id="" value="新增" /> </td> </tr> <tr> <td> <input type="button" class="sub-menu-btn" name="" id="" value="刪除" /> </td> </tr> <tr> <td> <input type="button" class="sub-menu-btn" name="" id="" value="待定" /> </td> </tr> </table> </div> <div> <p>右鍵點我</p> </div> <div> <p>右鍵點我</p> </div> <div> <p>右鍵點我</p> </div> <div> <p>右鍵點我</p> </div> <div> <p>右鍵點我</p> </div>
CSS
#sub-menu {
position: absolute; // 重要
z-index: 9999;
background: white;
border: 1px solid;
display: none;
}
.sub-menu-btn{
width: 100px;
background-color: white;
border: none;
}
JS
<script type="text/javascript"> $("#sub-menu").hide() $("p").on("contextmenu", function(e){ $("#sub-menu").show(100) $('#sub-menu').css({ 'top': e.pageY + 'px', 'left': e.pageX + 'px' }); return false; }) $(document).on('click', function(e) { var evt = event.srcElement ? event.srcElement : event.target; if (evt.id == 'sub-menu') { return; } else { $('#sub-menu').hide(); } }); </script>