jquery-11 如何製做鼠標右鍵菜單
1、總結
一句話總結:核心原理:找到右鍵菜單事件contextmenu,return false去掉默認事件,而後判斷用戶是否點的右鍵,而後在鼠標的位置顯示菜單。菜單弄成絕對定位,開始時設置爲不顯示。
一、右鍵菜單事件是什麼?
contextmenucss
40 $(document).contextmenu(function(event){
二、如何阻止默認的右鍵菜單事件?
在事件中return false能夠阻止事件的默認行爲html
40 $(document).contextmenu(function(event){ 41 x=event.clientX; 42 y=event.clientY; 43 44 btn=event.button; 45 46 if(btn==2){ 47 $('ul').show().css({'left':x+'px','top':y+'px'}); 48 return false; 49 } 50 });
三、如何使用事件發生的event對象?
事件發生會產生一個event對象,將它做爲參數傳遞給匿名函數,便可在匿名函數中操做它jquery
40 $(document).contextmenu(function(event){ 41 x=event.clientX; 42 y=event.clientY;
四、如何獲取鼠標在屏幕上面的位置?
有一個事件發生,將它的事件對象傳遞給匿名函數,在匿名函數中調用這個event對象的clientX和clientY便可獲取它的鼠標位置函數
40 $(document).contextmenu(function(event){ 41 x=event.clientX; 42 y=event.clientY;
五、如何判斷用戶是否點右鍵?
獲取event對象的button屬性,屬性值爲2便是鼠標右鍵,0左鍵,1滾輪。spa
44 btn=event.button; 45 46 if(btn==2){
六、如何將元素放在鼠標右鍵的位置?
先獲取鼠標的位置(event對象的clientX和clientY屬性),而後設置元素絕對定位,而後設置left和top屬性便可code
40 $(document).contextmenu(function(event){ 41 x=event.clientX; 42 y=event.clientY; 43 44 btn=event.button; 45 46 if(btn==2){ 47 $('ul').show().css({'left':x+'px','top':y+'px'}); 48 return false; 49 } 50 });
2、如何製做鼠標右鍵菜單
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>index</title> 6 <style> 7 *{ 8 margin:0px; 9 padding:0px; 10 } 11 12 ul{ 13 width:100px; 14 height:150px; 15 background: #ccc; 16 border-radius:10px; 17 position: absolute; 18 display: none; 19 } 20 21 ul li{ 22 text-align: center; 23 color:#fff; 24 font-weight: bold; 25 line-height: 25px; 26 } 27 </style> 28 <script src="jquery.js"></script> 29 </head> 30 <body> 31 <ul> 32 <li><a href='http://www.yzmedu.com' target='_blank'>雲知夢</a></li> 33 <li>第一菜單</li> 34 <li>第一菜單</li> 35 <li>第一菜單</li> 36 <li>第一菜單</li> 37 </ul> 38 </body> 39 <script> 40 $(document).contextmenu(function(event){ 41 x=event.clientX; 42 y=event.clientY; 43 44 btn=event.button; 45 46 if(btn==2){ 47 $('ul').show().css({'left':x+'px','top':y+'px'}); 48 return false; 49 } 50 }); 51 </script> 52 </html>