欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript 自定義html元素鼠標(biāo)右鍵菜單功能

 更新時(shí)間:2019年12月02日 13:50:41   作者:授客  
這篇文章主要介紹了JavaScript 自定義html元素鼠標(biāo)右鍵菜單功能,本文通過實(shí)例代碼給大家分享實(shí)現(xiàn)思路,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

自定義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)注明出處,謝謝!

相關(guān)文章

最新評(píng)論