区分鼠标和键盘触发onclick

发布于 2024-12-05 00:33:32 字数 536 浏览 1 评论 0原文

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

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

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

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

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

总是返回“键=未定义的鼠标按钮=0”

你能帮忙吗?

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>

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).

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);
}

always returns "key = undefined mouse button = 0"

Can you help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

悲欢浪云 2024-12-12 00:33:32

可以检查是否 event.screenX 和 event.screenY 为零。

$('a#foo').click(function(evt) {
  if (evt.screenX == 0 && evt.screenY == 0) {
    window.alert('Keyboard click.');
  } else {
    window.alert('Mouse click.');
  }
});

CodePen 上的演示

我无法保证它适用于所有浏览器,并且所有情况,但它的好处是不尝试检测通过键盘完成的“点击”。因此,该解决方案更可靠地检测“点击”,但代价是检测“点击”是否来自键盘或鼠标的可靠性稍差。如果您希望相反,请查看@Gonzalo 的答案

注意:我发现使用此方法的一个地方是 Chromium

Could check if event.screenX and event.screenY are zero.

$('a#foo').click(function(evt) {
  if (evt.screenX == 0 && evt.screenY == 0) {
    window.alert('Keyboard click.');
  } else {
    window.alert('Mouse click.');
  }
});

Demo on CodePen

I couldn't find a guarantee that it works in all browsers and all cases, but it has the benefit of not trying to detect a "click" done via the keyboard. So this solution detects "click" more reliably at the cost of detecting if it's from keyboard or mouse somewhat less reliably. If you prefer the reverse, look as the answer from @Gonzalo.

Note: One place I found using this method is Chromium

憧憬巴黎街头的黎明 2024-12-12 00:33:32

您可以使用 event.detail

if(event.detail === 0) {
    // keypress
} else {
    // mouse event
}

You can use event.detail

if(event.detail === 0) {
    // keypress
} else {
    // mouse event
}
指尖微凉心微凉 2024-12-12 00:33:32

您可以使用 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));

内联 onClick="" 不会帮助你,因为它总是会传递该点击事件,因为这就是它被捕获的方式。

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

我使用了一个按钮,这样在选项卡焦点期间可以更轻松地看到突出显示的节点,但它对任何节点的工作方式都是相同的。

You can create a condition with event.type

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

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));

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

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.

oО清风挽发oО 2024-12-12 00:33:32

您可以区分单击和键盘点击,捕获并丢弃按键时产生的 keydown 事件:

jQuery(function($) {
    $("a#foo").keydown(function() {
        alert("keyboard");
        return false;
    }).click(function() {
        alert("mouse");
        return false;
    })
})

http:// /jsfiddle.net/NuP2g/

You can differentiate between a click and a keyboard hit capturing and discarding the keydown event originated at the moment of the key press:

jQuery(function($) {
    $("a#foo").keydown(function() {
        alert("keyboard");
        return false;
    }).click(function() {
        alert("mouse");
        return false;
    })
})

http://jsfiddle.net/NuP2g/

Hello爱情风 2024-12-12 00:33:32

const isKeyboardClick = nativeEvent.detail === 0 && !nativeEvent.pointerType;

通过 detail 在常青浏览器中使用以下作品,并通过 pointerType 在 IE11 中使用以下作品。不适用于单选按钮 元素包裹的情况。

I use the following

const isKeyboardClick = nativeEvent.detail === 0 && !nativeEvent.pointerType;

Works in evergreen browsers via detail and IE11 via pointerType. Does not work for the case where e.g. radio button <input> is wrapped by a <label> element.

一江春梦 2024-12-12 00:33:32

如今,您可以使用 instanceof,它甚至具有完整的浏览器支持

function onMouseOrKeyboardSubmit(event, id) {
    if (event instanceof KeyboardEvent) {
        alert("Submitted via keyboard");
    } else if (event instanceof MouseEvent) {
        alert("Submitted via mouse");
    } else {
        alert("Unexpected submit event");
    }
}

Nowadays, you can make use of instanceof which even has full browser support.

function onMouseOrKeyboardSubmit(event, id) {
    if (event instanceof KeyboardEvent) {
        alert("Submitted via keyboard");
    } else if (event instanceof MouseEvent) {
        alert("Submitted via mouse");
    } else {
        alert("Unexpected submit event");
    }
}
万劫不复 2024-12-12 00:33:32

我知道这是一个老问题,但考虑到我花了多少时间寻找一个可行的、没有 jquery 和 IE 兼容的解决方案,我认为把它放在这里(我首先想到的地方)并不是一个坏主意。

我对此进行了测试,发现它工作正常:

let mouseDown = false;

element.addEventListener('mousedown', () => {
  mouseDown = true;
});

element.addEventListener('mouseup', () => {
  mouseDown = false;
});

element.addEventListener('focus', (event) => {
  if (mouseDown) {
    // keyboard
  } else {
    // mouse
  }
});

源链接:https://www. darrenlester.com/blog/focus-only-on-tab

I know this is an old question but given how much time I lost looking for a working, no jquery and IE-compatible solution, I think it won't be a bad idea to put it here (where I came first).

I tested this and found it working fine :

let mouseDown = false;

element.addEventListener('mousedown', () => {
  mouseDown = true;
});

element.addEventListener('mouseup', () => {
  mouseDown = false;
});

element.addEventListener('focus', (event) => {
  if (mouseDown) {
    // keyboard
  } else {
    // mouse
  }
});

Source link : https://www.darrenlester.com/blog/focus-only-on-tab

新一帅帅 2024-12-12 00:33:32

无法提出完全依赖事件的解决方案,但您可以将锚标记放置在按钮上,并为其指定 tabindex-1。这为您提供了一个可以聚焦并与键盘输入/空格键接合的按钮,并为您提供了一个可点击的表面,让您可以选择区分两个代码路径。

.button {
  position: relative;
}

.anchor {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
<button id="button" class="button">
  button
  <a class="anchor" href="#example" tabindex="-1"></a>
</button>

Wasn't able to come up with solution relying entirely on the events but you can position an anchor tag over a button and give it a tabindex of -1. This gives you a button that can be focused and engaged with keyboard enter/spacebar, as well as giving you a clickable surface that gives you an option to differentiate the two codepaths.

.button {
  position: relative;
}

.anchor {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
<button id="button" class="button">
  button
  <a class="anchor" href="#example" tabindex="-1"></a>
</button>

墨落画卷 2024-12-12 00:33:32

处理 mouseup 事件。
如果您随后立即点击,则可能是通过鼠标完成的。

Handle the mouseup event.
If you get a click right afterwards, it was probably done with the mouse.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文