jQuery – ContentMenu 簡易教學

下載位置

HTML 部份

<button id="btn">Right click me</button>

JavaScript 部份

//設定主選單內容
var menu_delete  = {name:"刪除", icon: "delete_new"}; // icon: "delete_new" 是自定義圖示
var menu_download = {name:"下載", icon:"download"};

var menu_add = {
   name:"新增",
   icon:"icon_add",
   disabled:function(action,data){
        return true; //禁止選取
   },
   visible: function(action,data){
       return true; //可看見
   }
}

var itemArr = {};
itemArr['download'] = menu_download;
itemArr['line'] = "-----------";  //分隔線
itemArr['delete'] = menu_delete;

設定二級選單內容
itemArr['subMenu']['items'] = {};

var tempObject = {};
tempObject['subMenuA'] = {"name": "二級選單 A"};
tempObject['subMenuB'] = {"name": "二級選單 B"};

itemArr['move']['items'] = tempObject;

var selector = $("#btn");
$.contextMenu('destroy', selector);   //清除指定selector原本的context menu 功能, 有需要才用
//$.contextMenu('destroy'); //清除所有context menu功能, 有需要才用

//套用context menu
$.contextMenu({
  selector: '#btn',
  callback: function(key, options){
    var element = $(this);

    console.log(key);   //顯示 download, delete 等字眼
  },
   items: itemArr
});

$("#btn").contextMenu('update');

CSS 部份

/* 自定義圖示 */
.context-menu-icon-delete_new{  /* delete_new 對應 icon 的名稱 */
    background-image: url("../icon/delete.png") !important;
    background-repeat: no-repeat;
    background-position: 6px 4px;
    background-size: 16px 16px;
}

/* PS: 原本的CSS 也有預設的圖示 */

更多詳情請參考

https://swisnl.github.io/jQuery-contextMenu/

開始在上面輸入您的搜索詞,然後按回車進行搜索。按ESC取消。

返回頂部