首页 > 语言 > JavaScript > 正文

在博客园博文中添加自定义右键菜单的方法详解

2024-05-06 15:44:07
字体:
来源:转载
供稿:网友

页面设计

首先将这三个功能以一个列表<ul>的形式放置。鼠标移入时样式改变,移出时还原

<style>body{margin: 0;}ul{  margin: 0;  padding: 0;  list-style: none;}.list{  width: 100px;  text-align: center;  cursor: pointer;  font:20px/40px '宋体';  background-color: #eee;}.in:hover{  background-color: lightblue;  color: white;  font-weight:bold;}</style><ul id="list" class="list">  <li class="in">顶部</li>  <li class="in">点赞</li>  <li class="in">评论</li></ul>

菜单逻辑

菜单逻辑共包括阻止默认行为、显隐效果和位置判断三个部分

默认行为

通常,点击右键时,会弹出浏览器的默认右侧菜单

通过return false可以实现阻止默认行为的效果,当然也可以使用preventDefault()和returnValue,详细信息移步至此

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

显隐

右键菜单默认隐藏,点击右键时显示,点击左键时再隐藏

关于元素显隐,个人总结过共9种思路,本文就用最简单的display属性

<div id="test" style="height: 100px;width: 100px;background-color: pink;"></div><script>document.onclick = function(){  test.style.display = 'none';}document.oncontextmenu = function(){  test.style.display = 'block';  return false;}</script>

位置判断

鼠标对象共有6对坐标位置信息,若把右键菜单设置为fixed固定定位,则选择clientX/Y即可

一般地,右键菜单的左上角位置应该是当前鼠标的坐标处

但是,还有另外2种情况需要考虑

【1】如果鼠标的位置到视口底部的位置小于菜单的高度,则鼠标的位置为菜单的底部位置

【2】如果鼠标的位置到视口右侧的位置小于菜单的宽度,则视口的右侧为菜单的右侧

元素的尺寸信息共有偏移尺寸offset、可视区尺寸client和滚动尺寸scroll,此时菜单的宽高应该为偏移尺寸offsetWidth/offsetHeight(全尺寸包含width、padding、border)

<div id="test" style="position:fixed;height: 100px;width: 100px;background-color: pink;"></div><script>document.onclick = function(){  test.style.display = 'none';}document.oncontextmenu = function(e){  e = e || event;  test.style.left = e.clientX + 'px';  test.style.top = e.clientY + 'px';  //注意,由于加法、减法的优先级高于大于、小于的优先级,所以不用加括号,详细情况移步至此  if(document.documentElement.clientHeight - e.clientY < test.offsetHeight){    test.style.top = e.clientY - test.offsetHeight + 'px';  }  if(document.documentElement.clientWidth - e.clientX < test.offsetWidth){    test.style.left = document.documentElement.clientWidth - test.offsetHeight + 'px';  }  test.style.display = 'block';  return false;}</script>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选