JS实现自定义鼠标右击菜单的代码怎么写

这篇“JS实现自定义鼠标右击菜单的代码怎么写”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“JS实现自定义鼠标右击菜单的代码怎么写”文章吧。

  代码如下:

  HTML代码

  <!DOCTYPEhtml>

  <html>

  <head>

  <metacharset="UTF-8">

  <metaname="viewport"content="width=device-width,initial-scale=1.0">

  <metahttp-equiv="X-UA-Compatible"content="ie=edge">

  <title>Document</title>

  <linkrel="stylesheet"type="text/css"href="right-click.css"/>

  </head>

  <body>

  <divid="contain-friend">右击显示菜单</div>

  <labelid="label1"></label>

  <divid="menu-friend">

  <div>

  <buttonid="btn1">菜单一</button>

  </div>

  <div>

  <buttonid="btn2">菜单二</button>

  </div>

  </div>

  <scriptsrc="right-click.js"></script>

  </body>

  </html>

  HTML

  JS代码

  关于菜单的定位主要是在第一个if语句部分,后面为验证按钮效果。

  menu1.style.left和menu1.style.top用于对菜单进行定位,由css样式表可知menu1的position属性定位为absolute,style.top定位相对于离它最近的position属性值不为static的父辈元素,此处即为body。

  menu的位置需要根据页面布局的具体情况来判断是e.offsetX/Y、e.clientX/Y或是其它,此处加上document.documentElement.scrollTop是考虑加上滚动条的情况(实际上这个例子里面并没有滚动条)。

  window.onload=function(){

  //以下为自定义右击菜单

  document.oncontextmenu=function(e){

  //阻止执行浏览器默认右击事件

  e.preventDefault();

  //聊天室好友列表

  if(document.getElementById("menu-friend")){

  varmenu1=document.getElementById("menu-friend");

  menu1.style.display="block";

  document.getElementById("contain-friend").onmousedown=function(e){//菜单定位

  menu1.style.left=e.offsetX+"px";

  menu1.style.top=document.documentElement.scrollTop+e.clientY+"px";

  //alert(menu1.style.top)

  if(document.getElementById("contain-friend")){

  if(e.button==2){

  menu1.style.visibility="visible";

  }else{

  menu1.style.visibility="hidden";

  }

  }

  }

  }

  }

  if(document.getElementById("btn1")){

  document.getElementById("btn1").onmousedown=function(e){

  document.getElementById("label1").innerHTML="你点击了菜单一"

  }

  }

  if(document.getElementById("btn2")){

  document.getElementById("btn2").onmousedown=function(e){

  document.getElementById("label1").innerHTML="你点击了菜单二"

  }

  }

  returnfalse;

  //与e.preventDefault();功能相同,但是必须放在最后否则在return后面的内容均不执行

  }

  JavaScript文件

  CSS样式表

  1/*自定义右击菜单*/

  .contain{

  background-color:#D1CEBC;

  height:100px;

  width:300px;

  }

  .menu{

  width:150px;

  background-color:white;

  visibility:hidden;

  position:absolute;

  box-shadow:0px0px10px#D1CEBC

  }

  .menu-item{

  background-color:#fff;

  margin:0;

  }

  .menu-item-btn{

  width:146px;

  margin:2px;

  border:0;

  text-align:left;

  padding-left:60px;

  padding-top:5px;

  padding-bottom:5px;

  background-color:#fff;

  color:#000;

  }

  .menu-item-btn:hover{

  background-color:#D1CEBC;

  }

以上就是关于“JS实现自定义鼠标右击菜单的代码怎么写”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注蜗牛博客行业资讯频道。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接