本文實例為大家分享了JavaScript實現點擊自制菜單效果的具體代碼,供大家參考,具體內容如下
應用場景:當我們希望用戶再點擊右鍵的時候不希望彈出瀏覽器的默認菜單時,需要阻止瀏覽器默認行為,并執(zhí)行我們想要的效果
第一種方式,通過創(chuàng)建元素的方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >Document</ title > < style > body { height: 3000px; } .menu { width: 100px; height: 280px; background-color: red; position: absolute; left: 0; top: 0; display: none; } </ style > </ head > < body > < script > var Bon = true; var menu = null; document.oncontextmenu = function(event) { if (Bon) { menu = document.createElement("div"); menu.classList.add("menu"); document.body.appendChild(menu); menu.style.left = event.pageX + "px"; menu.style.top = event.pageY + "px"; menu.style.display = "block"; Bon = false; event.preventDefault(); } else { menu.style.left = event.pageX + "px"; menu.style.top = event.pageY + "px"; event.preventDefault(); } } document.onmousedown = function(e) { if (e.button == 0) { var menu = document.querySelector(".menu"); document.body.removeChild(menu); Bon = true; } } </ script > </ body > </ html > |
第二種:通過隱藏元素的方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
< div class = "menu" ></ div > < script > var menu = document.querySelector(".menu"); document.oncontextmenu = function(event) { menu.style.left = event.pageX + "px"; menu.style.top = event.pageY + "px"; menu.style.display = "block"; event.preventDefault(); } document.onmousedown = function(e) { if (e.button == 0) { menu.style.display = "none"; } } </ script > |
當我們點擊右鍵時就不會彈出默認的菜單了,彈出了我設置的紅框框。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/weixin_45773503/article/details/113425737