Simulate left and right arrow key event with javascript

风格不统一 提交于 2019-11-26 16:36:32

问题


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


回答1:


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/

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.




回答2:


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'



来源:https://stackoverflow.com/questions/5516600/simulate-left-and-right-arrow-key-event-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!