js自訂滑鼠右鍵的實現原理及源碼

來源:互聯網
上載者:User

今天來記錄下js來自訂滑鼠右鍵,同樣先來分解下它的實現原理:

1、屏蔽右鍵預設事件;(一度我以為修改的就是預設事件)

2、對一個ul的隱藏;(這個我也曾迂腐的認為值得這樣操作的都是div,汗)

3、對滑鼠點擊右鍵做出的響應,顯示隱藏的ul;

4、滑鼠重新點擊後,ul重新被隱藏

這樣來看的話,我們需要做的事情是不是就簡單了很多,先上代碼:

html部分

<ul id="testRight" style="width: 100px;background-color: yellow;position: absolute;z-index: 100;"> <li><a href="#">開始</a></li> <li><a href="#">暫停</a></li> <li><a href="#">拜拜</a></li> </ul>

javascript部分:

window.onload=function(){ var forRight=document.getElementById("testRight");//擷取對象,現在太熟悉了 forRight.style.display="none"; var title=forRight.getElementsByTagName("li"); for(var i=0;i<title.length;i++){ title[i].onmouseover=function(){ this.classname="active";//其實這裡我們也可以調用其他事件吧 }; title[i].onmouseout=function(){//這裡也是滑鼠的兩個事件吧 this.classname=""; }; } document.oncontextmenu=function(event){//這是實現的關鍵點 var event=event||window.event;//這個都不是問題了吧 forRight.style.display="block"; forRight.style.left=event.clientX+"px"; forRight.style.top=event.clientY+"px";//滑鼠的座標啊 return false;//這裡返回false就是為了屏蔽預設事件 }; document.onclick=function(){//就是為了更形象的模仿啊 forRight.style.display="none"; }; };


先來看今天記錄的最關鍵的地方:document.oncontextmenu這個事件返回false的話就是屏蔽預設事件,如果我們其他都不寫,只在這個事件裡面寫return,好像就下面這樣

document.oncontextmenu=function(){ return false; }

這樣的話,再點擊右鍵也不會出現任何響應了。然後返回來再看整個的事件應用,好像除了這個事件,其他的都是比較熟悉的事件了,可就是對事件的這種整合總是缺乏,關鍵還是思路是創意吧,不過先不管哪兒多了,先整吧,但求熟讀三千首,不求寫來只問吟。紮馬步,紮馬步,紮馬步.....

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.