我可以在HTML<按钮/>上处理右键单击事件吗?元件? [英] Can I handle a right click event on an HTML <button /> element?

查看:123
本文介绍了我可以在HTML<按钮/>上处理右键单击事件吗?元件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SO和其他地方看到了很多关于右键单击事件以及如何使用JavaScript来捕获和处理它们的问题和答案,通常使用 .button 浏览器生成的事件对象的属性。



然而,我没有发现的一件事,可能因为这是一个非常奇怪的请求,是如何捕获并处理HTML < button /> 元素上的右键单击。浏览器按钮的处理方式与其他元素的处理方式不同。最重要的是,似乎右键单击按钮没有任何作用。没有上下文菜单,从我可以告诉,没有事件。



我错了吗?我希望如此,因为这会让我的生活更轻松。如果没有,我可以模拟一个div和一些CSS的按钮,但我宁愿避免它。任何想法?



(PS:这是一个愚蠢的项目,所以不要担心我试图将基于按钮的右键单击界面放在前面任何客户或任何东西,我很清楚接口可能会有多糟糕。)

解决方案

当然,只需添加

JS:

  document.getElementById(test)。onmousedown = function(event){
if(event.which == 3){
alert( 右键点击!);


$ / code $ / pre
$ b

HTML:

 < button id =test>测试< /按钮> 

演示: http://jsfiddle.net/Jmmqz/


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 .button attribute of the event object generated by the browser.

However, the one thing I haven't found, probably because it's a pretty weird request, is how to catch and handle right clicks on an HTML <button /> element. Buttons are not handled the same way by the browser as other elements. Most importantly, it seems that a right click on a button doesn't do anything. No context menu and, from what I can tell, no event.

Am I wrong? I hope so, because it will make my life easier. If not, I can simulate a button with a div and some CSS, but I'd rather avoid it. Any thoughts?

(PS: This is for a silly side project, so don't worry about me trying to put a button-right-click-based interface in front of any customers or anything. I'm well aware of how horrible that interface would probably be.)

解决方案

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/

这篇关于我可以在HTML&lt;按钮/&gt;上处理右键单击事件吗?元件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆