用jQuery修改右键菜单

概述

以前在网上找过屏蔽右键菜单的代码,也找过屏蔽F12的代码,今天无意之中看到别人的右键菜单很有意思,我也想来搞一个。

思路

  1. 建立一个菜单并且隐藏起来。
  2. 用window.oncontextmenu屏蔽鼠标右键的默认事件。
  3. 判断鼠标点击事件的类型,如果为右键则在把菜单显示并且移动到鼠标位置。
  4. 点击鼠标左键时,隐藏菜单。

代码示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <style>
        li {
            cursor: pointer;
        }
        li:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body style="position: relative;">
<div style="background-color: grey; width: 500px; height: 500px;"></div>
<ul class="right" style="display: none;position: absolute;border: 1px solid green">
    <li>喵喵!!</li>
    <li>不准偷看</li>
    <li>关于本站</li>
</ul>

<script type="text/javascript">
    window.oncontextmenu = function() { return false; };
    $('body').mousedown(function(event) {
        if (event.which === 3) {
            $('.right').css({ 'display': 'block', 'top': event.pageY + 'px', 'left': event.pageX + 'px' });
        }
    });
    $('body').click(function(event) {
        $('.right').css({ 'display': 'none' });
    });
</script>
</body>
</html>

运行测试

Document <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
  • 喵喵!!
  • 不准偷看
  • 关于本站
<script> window.oncontextmenu = function() { return false; }; $('body').mousedown(function(event) { if (event.which === 3) { $('.right').css({ 'display': 'block', 'top': event.pageY + 'px', 'left': event.pageX + 'px' }); } }); $('body').click(function(event) { $('.right').css({ 'display': 'none' }); }); </script>

其它

有一个小bug,就是当把那个长宽500px的div删掉时,就不会触发事件了,原因不明。

不是position的问题,因为我把这个div的长宽设置为1px后,在远离它的地方点击不会触发事件,在靠近它的地方点击则会触发事件。

哈哈,原因找到了!并不是没有触发事件,而是因为html的body没有被撑开,所以不能把这个div通过绝对定位移动到body以外

实测,去掉这个div,然后给body加上这个样式style="width: 100%; height: 2000px;"就可以了。

转载于:https://www.cnblogs.com/yangzhou33/p/8598323.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值