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

js實(shí)現(xiàn)右鍵彈出自定義菜單

 更新時(shí)間:2020年09月08日 15:30:26   作者:txx_laughing  
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)右鍵彈出自定義菜單,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

近期在項(xiàng)目中有一個(gè)右鍵菜單的需求,發(fā)現(xiàn)很多實(shí)現(xiàn)都比較復(fù)雜,于是自己花了一點(diǎn)時(shí)間稍微研究了一下,下面提供一個(gè)簡(jiǎn)潔的實(shí)現(xiàn)方法。

js聲明部分:

//創(chuàng)建右鍵菜單
var epMenu={
  create:function(point,option){
    var menuNode=document.getElementById('epMenu');
    if(!menuNode){
      //沒(méi)有菜單節(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)的右鍵菜單,非常重要?。。?/p>

最后,這個(gè)簡(jiǎn)易的右鍵菜單功能還有點(diǎn)瑕疵,右鍵菜單彈出后,不進(jìn)行菜單項(xiàng)點(diǎn)擊操作,菜單不會(huì)自動(dòng)關(guān)閉,后期有空再完善吧。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論