Can I handle a right click event on an HTML <button /> element?

前端 未结 4 1759
孤街浪徒
孤街浪徒 2020-12-31 11:11

I\'ve seen plenty of questions and answers on SO and elsewhere that talk about right click events and how to catch and handle them with JavaScript, generally using the

相关标签:
4条回答
  • 2020-12-31 11:44

    Sure, just add a onmousedown listener, check which mouse was pressed:

    JS:

    document.getElementById("test").onmousedown = function(event) {
        if (event.which == 3) {
            alert("right clicked!");
        }
    }
    

    HTML:

    <button id="test">Test</button>
    

    Demo: http://jsfiddle.net/Jmmqz/

    0 讨论(0)
  • 2020-12-31 11:45

    http://jsfiddle.net/jqYN5/ is this what you are looking for? Adding context-menu:

    <input type="button" value="click me" id="btn">
    <button id="btn2">right click</button>`
    
    document.getElementById('btn').onclick = function() {
      alert('click!')
    }
    
    document.getElementById('btn2').oncontextmenu = function() {
      alert('right click!')
    }
    
    0 讨论(0)
  • 2020-12-31 11:48

    You can make use of "context Menu" also :

    document.getElementById('btn2').oncontextmenu = function() {
     alert('right click!')
    }
    
    0 讨论(0)
  • 2020-12-31 11:51

    Or, with perhaps a bit more beginner level understanding:

    <script type="text/javascript">
    function mouseclick(ele, e) {
    if (e.type == 'click') {
        alert('Left Click Detected!');
    }
        if (e.type == 'contextmenu') {
        alert('Right Click Detected!');
    }
    }
    </script>
    
    <a href="/" 
    onclick="mouseclick(this, event)" 
    oncontextmenu="mouseclick(this, event)" >link name</a>
    
    0 讨论(0)
提交回复
热议问题