1. 程式人生 > >JS自定義右鍵選單—複製到貼上板(jQuery和原生JS實現)

JS自定義右鍵選單—複製到貼上板(jQuery和原生JS實現)

##自定義右鍵選單——複製到貼上板
####需求:

  1. 滑鼠在li標籤上點選右鍵出現選單,主要是複製等功能

  2. 遮蔽瀏覽器預設右鍵點選事件

  3. 右鍵選單出現在滑鼠點選的位置

  4. 點選螢幕其他位置選單消失

  5. 點選之後有回撥
    ###實現:
    ####1、使用jQuery - 右鍵選單外掛contextMenu

  6. 在專案中引入jquery.contextMenu.jsjquery.contextMenu.css
    同時 contextMenu 依賴 jQuery。

  7. 初始化外掛

     $.contextMenu({
         selector: 'li',
         callback: function(key, options) {
             var Url2 = $(this).text().trim();
             var oInput = document.createElement('input');
             oInput.value = Url2;
             document.body.appendChild(oInput);
             oInput.select(); // 選擇物件
             document.execCommand("Copy"); // 執行瀏覽器複製命令
             oInput.className = 'oInput';
             oInput.style.display = 'none';
             alert('成功複製到貼上板');
         },
         items: {
             "copy": { name: "複製", icon: "copy" },
         }
     });
    

搞定!成功複製到貼上板。
#####contextMenu外掛:GitHub 主頁
#####contextMenu外掛:使用方法
####2、使用原生js手擼一個
直接上程式碼:
#####html:



  • 複製

  • 刪除



#####CSS:
* {
margin: 0;
padding: 0;
}
    #Rmenu {
        width: 80px;
        background: #00AAAA;
        position: absolute;
        display: none;
        color: #fff;
        text-align: center;
        border-radius: 5px;
        cursor: pointer;
        -moz-box-shadow: 2px 2px 20px #333333;
        -webkit-box-shadow: 2px 2px 20px #333333;
        box-shadow: 2px 2px 20px #333333;
    }
    
    #Rmenu ul li:hover {
        font-size: 17px;
        background-color: #E1B700;
    }
    
    #Rmenu ul li {
        border-radius: 5px;
        list-style: none;
        margin: 5px;
        font-size: 16px;
    }

#####JS
window.onload = function() {
var menu = document.getElementById(“Rmenu”);
document.oncontextmenu = function(ev) {
var ev = ev || event;
menu.style.display = “block”;
menu.style.left = ev.clientX + “px”;
menu.style.top = ev.clientY + “px”;
//阻止預設右鍵事件
return false;
}
document.onclick = function(e) {
//click事件可以關閉右鍵選單
if (e.target.tagName.toLowerCase() === ‘li’) {
console.log(“您點選的是:” + e.target.outerText);
}
menu.style.display = “none”; 
}
}
結果: