溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

利用js實(shí)現(xiàn)一個(gè)右鍵彈出自定義菜單功能

發(fā)布時(shí)間:2020-11-04 16:29:19 來(lái)源:億速云 閱讀:319 作者:Leah 欄目:開發(fā)技術(shù)

今天就跟大家聊聊有關(guān)利用js實(shí)現(xiàn)一個(gè)右鍵彈出自定義菜單功能,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

js聲明部分:

//創(chuàng)建右鍵菜單
var epMenu={
  create:function(point,option){
    var menuNode=document.getElementById('epMenu');
    if(!menuNode){
      //沒有菜單節(jié)點(diǎn)的時(shí)候創(chuàng)建一個(gè)
      menuNode=document.createElement("div");
      menuNode.setAttribute('class','epMenu');
      menuNode.setAttribute('id','epMenu');
    }else $(menuNode).html('');//清空里面的內(nèi)容

    $(menuNode).css({left:point.left+'px',top:point.top+'px'});
    for(var x in option){
      var tempNode=document.createElement("a");
      $(tempNode).text(option[x]['name']).on('click',option[x].action);
      menuNode.appendChild(tempNode);
    }

    $("body").append(menuNode);
  },
  destory:function(){
    $(".epMenu").remove();
  }  
};

function sayhello(){
  alert("hellokity");
  epMenu.destory();
}

function hideSysMenu() {
  return false;
}

css樣式定義部分:

.epMenu{ width:120px; background:#f0f0f0; position:fixed; left:0; top:0; box-shadow:2px 2px 2px 2px #807878;}
.epMenu a{ display:block; height:25px; line-height:25px; padding-left:15px; border-top:1px solid #e0e0e0; border-bottom:1px solid #fff; font-family:微軟雅黑; font-size:14px; cursor:default;}
.epMenu a:hover{ background:#fff;}

下面就是菜單的自定義調(diào)用部分了:

document.onmousedown = function(e){
    var menuNode=document.getElementById('epMenu');
    if(e.button===2){
      document.oncontextmenu = hideSysMenu;//屏蔽鼠標(biāo)右鍵
      var evt = window.event || arguments[0];
      var rightedge = evt.clientX;
      var bottomedge = evt.clientY;
      epMenu.create({left:rightedge,top:bottomedge},[{name:'a1','action':sayhello},{name:'b2','action':sayhello},{name:'c3','action':sayhello},{name:'c4','action':sayhello}]);  
    }
//   epMenu.destory();
  }

簡(jiǎn)單解析一下:

1、epMenu.create方法的第一個(gè)參數(shù)是菜單彈出的位置坐標(biāo)(距離屏幕左上角),這里用的是鼠標(biāo)點(diǎn)擊的坐標(biāo),菜單跟隨鼠標(biāo)點(diǎn)擊彈出;第二個(gè)參數(shù)是一個(gè)json格式的數(shù)據(jù),用于自定義菜單項(xiàng),name是菜單項(xiàng)名字,action是點(diǎn)擊菜單項(xiàng)后的動(dòng)作(可以是函數(shù),ajax請(qǐng)求等)。

2、e.button的值:2表示點(diǎn)擊右鍵,0表示點(diǎn)擊左鍵,4表示點(diǎn)擊中鍵(ie),各瀏覽器的button值不同,此處僅以ie11作為參考。

3、注意在創(chuàng)建自定義菜單之前一定要屏蔽系統(tǒng)默認(rèn)的右鍵菜單,非常重要?。?!

看完上述內(nèi)容,你們對(duì)利用js實(shí)現(xiàn)一個(gè)右鍵彈出自定義菜單功能有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI