Javascript和jquery事件--鼠標右鍵事件,contextmenu


右鍵點擊觸發是瀏覽器的默認菜單事件contextmenu,你可以選擇阻止它,使用event.preventDefault();或者return false;。

想要定義右鍵點擊事件,關注的是mouseup或者mousedown事件,使用event獲取點擊的鍵:

Js中使用event. button---0,1,2分別是左鍵、滾輪、右鍵

Jq中使用event.which---1,2,3分別是左鍵、滾輪、右鍵

<!DOCTYPE html>  
<html lang="zh-cn">  
    <head>  
        <meta charset="UTF-8"/>  
        <title>鼠標事件</title>  
        <script src='/static/Lib/jquery/jquery-3.3.1.min.js'></script>
        <script src='js/jquery-3.3.1.min.js'></script>
        <style>
            #f1{
                padding:10px;
                background:black;
            }
            #f2{
                padding:10px;
                background:red;
            }
            #f3{
                padding:10px;
            }
            #test{
                background:black;
                color:white;
                padding:2px;
            }
        </style>
    </head>  
    <body>  
        <div id="f1">
            <button id="button1">javascript</button>
        </div>
        <div id="f2">
            <button id="button2">jquery</button>
        </div>
        <div id='f3'><a href="worker.js" target="_blank" id='test'><span></span>超鏈接</a></div>
        <script type="text/javascript">  
        function say(){
            alert(this.innerHTML);
        }
        window.onload= function(){
            //實現右鍵單擊事件
            //js
            //關閉鼠標右鍵默認事件
            document.getElementById("button1").oncontextmenu = function(e){
                e.preventDefault();
            };
            //設置鼠標按鍵事件
            document.getElementById("button1").onmousedown = function(e){
                 if(e.button ==2){
                     console.log("你點了右鍵");
                 }else if(e.button ==0){
                     console.log("你點了左鍵");
                 }else if(e.button ==1){
                     console.log("你點了滾輪");
                 }
             }
             //jq
             //關閉鼠標右鍵默認事件
            $('#button2').bind("contextmenu", function(){
                return false;
            });
            //設置鼠標按鍵事件
            $('#button2').on('mousedown', function(e){
                if (1 == e.which) {
                    console.log("你點了左鍵");
                } else if (2 == e.which) {
                    console.log("你點了滾輪");
                } else if (3 == e.which) {
                    console.log("你點了右鍵");
                }
            });

            
        };
        
        
        </script>  
    </body>  
</html>  
示例html和js代碼

 

https://www.cnblogs.com/chenluomenggongzi/p/5777545.html

https://blog.csdn.net/u014291497/article/details/52267604


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM