Javascript 用javascript模拟左右箭头键事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5516600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simulate left and right arrow key event with javascript
提问by Trevor Rudolph
I'm using the slide.html5rocks.com framework and I'm trying to use to img tags inside of a tag links and I can't get the JavaScript onclick to simulate the left and right key events to change slides
我正在使用 slide.html5rocks.com 框架,我正在尝试在标签链接内使用 img 标签,但我无法使用 JavaScript onclick 来模拟左右键事件来更改幻灯片
回答by
You're looking for something that will dispatch an event. Here's something that should work:
您正在寻找可以调度事件的东西。这是应该起作用的东西:
function fireKey(el)
{
//Set key to corresponding code. This one is set to the left arrow key.
var key = 37;
if(document.createEventObject)
{
var eventObj = document.createEventObject();
eventObj.keyCode = key;
el.fireEvent("onkeydown", eventObj);
}else if(document.createEvent)
{
var eventObj = document.createEvent("Events");
eventObj.initEvent("keydown", true, true);
eventObj.which = key;
el.dispatchEvent(eventObj);
}
}
I made a cool little interface test with it that will probably interest you. Here's how it looks: http://jsfiddle.net/FvCut/6/
我用它做了一个很酷的小界面测试,你可能会感兴趣。这是它的外观:http: //jsfiddle.net/FvCut/6/
Tested as working in Firefox 3.6, Opera 11, Safari 5, IE 8, and IE 7/IE Quirks Mode. Of note: Opera 11 doesn't fire repeated "keydown" events when you hold a key down like most browsers.
经测试可在 Firefox 3.6、Opera 11、Safari 5、IE 8 和 IE 7/IE Quirks 模式下工作。值得注意的是:Opera 11 不会像大多数浏览器一样在您按住某个键时触发重复的“keydown”事件。
回答by daniellmb
How are you simulating the event? document.dispatchEvent doesn't work in all browsers.
You can test the feature using this: typeOf(document.dispatchEvent) != 'undefined'
你是如何模拟事件的?document.dispatchEvent 不适用于所有浏览器。您可以使用以下方法测试该功能:typeOf(document.dispatchEvent) != 'undefined'