当前位置 : 主页 > 网页制作 > html >

网页开发利用jq自定义鼠标右击事件

来源:互联网 收集:自由互联 发布时间:2021-06-12
1 ! DOCTYPE html 2 html 3 head 4 meta charset ="UTF-8" 5 title 鼠标右键事件 / title 6 !-- 引入jq -- 7 script type ="text/javascript" src ="../jquery-3.3.1/jquery-3.3.1.min.js" / script 8 style type ="text/css" 9 .view { 10 width : 5
 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>鼠标右键事件</title>
 6     <!-- 引入jq -->
 7     <script type="text/javascript" src="../jquery-3.3.1/jquery-3.3.1.min.js"></script>
 8     <style type="text/css">
 9         .view{
10             width: 500px;
11             height: 500px;
12             margin: 0px auto;
13             background-color: #999;
14         }
15         #r_click{
16             position: fixed;width: 120px;height: 60px;border: solid 1px #ccc;background-color: #fff;
17             cursor: pointer;
18         }
19         #r_click>div:nth-child(1){
20             border-bottom: solid 1px #ccc
21         }
22         #r_click>div{
23             height: 30px;
24             line-height: 30px;
25             text-align: center;
26             font-size: 14px;
27         }
28         #r_click>div:hover{
29             background-color: #ccc;
30         }
31     </style>
32 </head>
33 <body>
34 <div class="view" id="view">
35 </div>
36 <script>
37     window.onload =function () {
38         var el = document.getElementById("view");
39         var html = <div id="r_click"> +
40             <div>右点击1</div> +
41             <div>右点击2</div> +
42             </div>;
43         el.oncontextmenu = function(e) {
44             //左键--button属性=1,右键button属性=2
45             r_clickCancel();
46             if(e.button == 2) {
47                 e.preventDefault();
48                 var _x = e.clientX,
49                     _y = e.clientY;
50                 var layer_obj=$(html).css({
51                     display:"block",
52                     left:_x + "px",
53                     top:_y + "px"
54                 })
55                 $(body).append(layer_obj);
56             }
57         }
58     }
59     //绑定全局取消右击弹层事件
60     $(function () {
61         $(body).click(function () {
62             r_clickCancel()
63         })
64     })
65 
66     /**
67      * 隐藏右击弹层
68      * @returns {boolean}
69      */
70      function r_clickCancel(){
71         var layer_click=$(#r_click)
72         if(layer_click.length>=1){
73             layer_click.remove();
74         }
75         return false;
76     }
77 </script>
78 </body>
79 </html>
网友评论