区分鼠标和键盘触发onclick [英] Differentiate between mouse and keyboard triggering onclick

查看:253
本文介绍了区分鼠标和键盘触发onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到一种方法来确定是否通过鼠标点击或按键激活了链接。

I need to find a way to determine if a link has been activated via a mouse click or a keypress.

<a href="" onclick="submitData(event, '2011-07-04')">Save</a>

这个想法是,如果他们使用鼠标点击链接,那么他们可以继续使用鼠标选择他们下一步做什么。但是如果他们在页面上标签并且他们选择了保存链接,那么我将打开然后下一行进行编辑(该页面就像一个电子表格,每行都可以使用ajax编辑)。

The idea is that if they are using a mouse to hit the link then they can keep using the mouse to choose what they do next. But if they tabbing around the page and they tab to the Save link, then I'll open then next line for editing (the page is like a spreadsheet with each line becoming editable using ajax).

我认为可以查询事件参数是否按下了哪个鼠标按钮,但是当没有按下任何按钮时,答案为0,这与鼠标左键相同。他们认为我可以从事件中获取keyCode,但是它会以未定义的形式返回,所以我假设鼠标事件不包含该信息。

I thought the event parameter could be queried for which mouse button is pressed, but when no button is pressed the answer is 0 and that's the same as the left mouse button. They I thought I could get the keyCode from the event but that is coming back as undefined so I'm assuming a mouse event doesn't include that info.

function submitData(event, id)
{
    alert("key = "+event.keyCode + "  mouse button = "+event.button);
}

始终返回key = undefined mouse button = 0

always returns "key = undefined mouse button = 0"

你能帮忙吗?

推荐答案

你可以用 event.type

function submitData(event, id)
{
    if(event.type == 'mousedown')
    {
        // do something
        return;
    }
    if(event.type == 'keypress')
    {
        // do something else
        return;
    }
}

注意:你需要附上一个事件,支持两种事件类型。使用JQuery,它看起来像 $('a.save')。bind('mousedown keypress',submitData(event,this));

Note: You'll need to attach an event which supports both event types. With JQuery it would look something like $('a.save').bind('mousedown keypress', submitData(event, this));

内联 onClick =对你没有帮助,因为它总是会传递点击事件,因为它是如何被困的。

The inline onClick="" will not help you as it will always pass that click event since that's how it's trapped.

编辑这是一个工作演示,用原生JavaScript证明我的情况: http://jsfiddle.net/AlienWebguy/HPEjt/

EDIT: Here's a working demo to prove my case with native JavaScript: http://jsfiddle.net/AlienWebguy/HPEjt/

我用过一个按钮,因此在选项卡焦点期间更容易看到节点突出显示,但它对任何节点都有效。

I used a button so it'd be easier to see the node highlighted during a tab focus, but it will work the same with any node.

这篇关于区分鼠标和键盘触发onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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