模拟按住 Ctrl 键
我目前正在尝试更改多选元素的默认行为,以便用户可以选择和取消选择多个值,而不必一直按 Ctrl 键。
我找到了一个简单的解决方案 此处,但这在 ie8 中不起作用(因为在 ie 中,onmousedown
不适用于选项元素)。
但我想,只要鼠标悬停在多选上,就可以模拟按下的控制键:
$(document).ready(function() {
$('select').hover(function(e) {
var kde = jQuery.Event("keydown");
kde.ctrlKey = true; //something like this
kde.keyCode = 17; //or this - i don't know
$(e.target).trigger(kde);
});
});
为什么这不起作用?
- Ctrl 键是否再次被直接释放?
- 代码有问题吗?
- 我完全错过了其他东西吗?
I'm currently trying to change the default behaviour of a multiselect element, so that a user can select and deselect multiple values, without having to press the Ctrl key all the while.
I found a simple solution here, but this does not work in ie8 (because in ie, the onmousedown
does not apply to option elements).
But I figured, that one could just simulate a pressed control key, whenever the mouse hovers over a multiselect:
$(document).ready(function() {
$('select').hover(function(e) {
var kde = jQuery.Event("keydown");
kde.ctrlKey = true; //something like this
kde.keyCode = 17; //or this - i don't know
$(e.target).trigger(kde);
});
});
Why does this not work?
- Is the Ctrl key directly being released again?
- Is something wrong with the code?
- Am I missing something else entirely?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法通过以编程方式按下键盘按钮来模拟此类事件,就像您无法通过在用户按下 a 键时模拟 shift 键来生成大写 A 一样。他们的键盘。此外,即使它能工作,它也不会工作:在Mac上,你按cmd而不是ctrl来选择多个元素。
因此,不幸的是,您将不得不放弃这种方法并寻找其他选择。
You can't simulate such events by programmatically pushing keyboard buttons, just like you can't produce a capital A by simulating the shift key while the user pushes the a key on their keyboard. Besides, even if it would work it wouldn't work: on Macs you press cmd, not ctrl, to select multiple elements.
So unfortunately you'll have to drop this approach and look for other options.
您可能需要为每个项目添加一个复选框,而不是一个多选控件。
在代码中编写在选择新函数时取消选中其他函数的函数比阻止这种默认行为更容易。
You probably need to add a check box for each of your items, rather than a multi select control.
It is easier in code to write functions which uncheck the others when a new one is selected than to prevent this default behaviour.