Simulate left and right arrow key event with javascript

前端 未结 2 1502
不思量自难忘°
不思量自难忘° 2020-12-03 08:26

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

相关标签:
2条回答
  • 2020-12-03 08:56

    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.

    0 讨论(0)
  • 2020-12-03 09:04

    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'

    0 讨论(0)
提交回复
热议问题