js右击事件 您所在的位置:网站首页 js绑定鼠标右击事件是什么 js右击事件

js右击事件

2024-04-25 01:54| 来源: 网络整理| 查看: 265

先贴代码:

1 DOCTYPE html> 2 3 4 5 6 7 window.onload = function(){ 8 //去掉默认的contextmenu事件,否则会和右键事件同时出现。 9 document.oncontextmenu = function(e){ 10 e.preventDefault(); 11 }; 12 document.getElementById("test").onmousedown = function(e){ 13 if(e.button ==2){ 14 alert("你点了右键"); 15 }else if(e.button ==0){ 16 alert("你点了左键"); 17 }else if(e.button ==1){ 18 alert("你点了滚轮"); 19 } 20 } 21 } 22 23 24 25 26 27 28 View Code

注意的两个点是:

①:先取消默认右击事件,event.preventDefault();

②:判断event.Button:0:左键,1:滚轮,2:右键。

值得一说的的是"oncontextmenu"是指右键按下时的作用。

再给一个应用吧:

右击div显示出自己定义的菜单,点击除了div的地方,是默认的右击事件。

代码:

1 DOCTYPE html> 2 3 4 5 Title 6 7 body{ 8 margin: 0; 9 } 10 #menu{ 11 width: 100px; 12 height: 100px; 13 background-color: aquamarine; 14 text-align: center; 15 position: absolute; 16 left: 0; 17 top:0; 18 display: none; 19 } 20 #div{ 21 width: 400px; 22 height: 400px; 23 background-color: red;; 24 } 25 26 27 28 29 lalala 30 31 32 33 34 html 1 /** 2 * Created by Administrator on 2016/8/12. 3 */ 4 (function () { 5 6 var menu = document.querySelector("#menu"); 7 var div = document.querySelector("#div"); 8 var p=document.querySelector("#p"); 9 div.addEventListener("contextmenu", function (event) { 10 event.preventDefault(); 11 menu.style.display = "block"; 12 menu.style.left = event.pageX + "px"; 13 menu.style.top = event.pageY + "px"; 14 p.addEventListener("click",function () { 15 alert("a"); 16 }); 17 }); 18 document.addEventListener("contextmenu", function (event) { 19 if (event.pageX > 400 || event.pageY > 400) { 20 menu.style.display = "none"; 21 } 22 }); 23 })(); js

效果自行查看吧,其实也没啥。

原理是,右键的菜单其实是一个隐藏的div,当点击父类div的时候,它出现而已。(貌似这样一说显得这个程序好垃圾啊,╮(╯▽╰)╭其实这也是大厦的一块砖,少了它,大厦会塌的)

再给了类似的应用吧,一个点击div消失的效果。

1 DOCTYPE html> 2 3 4 5 点击消失 6 7 #m{ 8 width: 300px; 9 height: 300px; 10 } 11 #div{ 12 width: 100%; 13 height:100%; 14 background-color: red; 15 } 16 17 18 19 20 21 22 23 24 25 html 1 /** 2 * Created by Administrator on 2016/8/8. 3 */ 4 (function () { 5 6 var width = 100; 7 var height = 100; 8 var opacity = 1; 9 var div = document.getElementById("div"); 10 var time; 11 12 function clickToNone() { 13 // width-=20; 14 width -= 10; 15 height -= 10; 16 opacity -= 0.1; 17 div.style.width = width + "%"; 18 div.style.height = height + "%"; 19 div.style.opacity = opacity; 20 if (width == 0) { 21 div.style.display = "none"; 22 clearInterval(time); 23 // div.style.opacity=0; 24 } 25 } 26 27 function clickTo() { 28 time = setInterval(clickToNone, 300); 29 } 30 31 div.addEventListener("click", clickTo); 32 33 })(); js

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有