0

I'm trying to add arrow key navigation to this image gallery.

It should work similar to this

var chosen = "";
$(document).keydown(function (e) { // 38-up, 40-down
    if (e.keyCode == 40) {
        if (chosen === "") {
            chosen = 0;
        } else if ((chosen + 1) < $('li.t').length) {
            chosen++;
        }
        $('li.t').removeClass('selected');
        $('li.t:eq(' + chosen + ')').addClass('selected');
        $('li.t').click(this);
        return false;
    }
    if (e.keyCode == 38) {
        if (chosen === "") {
            chosen = 0;
        } else if (chosen > 0) {
            chosen--;
        }
        $('li.t').removeClass('selected');
        $('li.t:eq(' + chosen + ')').addClass('selected');
        $('li.t').click(this);
        return false;
    }
});

…but I want each arrow key press to work like a click since it should load a page in the iframe and at the same time perform another click action (moving the yellow frame to the newly selected thumbnail) just like it does now when clicking.

Also it would be great if going down with the arrow keys could force scrolling to keep the selected thumbnail in view.

…if I got this to work I imagine the next issue I'd run into would be that I would lose focus on the main page and the arrow key navigation whenever something is clicked within the iframe. This is a negligible issue but if there was a simple solution for it I would like to use it.

Thanks.

4

1 回答 1

0

使用您提供的 jsfiddle,您可以使用 jquery 的 trigger() 方法模拟用户点击。

$('li:eq('+whichIndex+') a').trigger("click");

这将导致单击事件上的当前代码运行。这样您就不必担心有逻辑来跟踪点击或按键。

Javascript

var chosen = "";
$(document).keydown(function(e){ // 38-up, 40-down
    chosen = $('li.selected').index(); //grab the current selection
    if (e.keyCode == 40) { 
        if(chosen === "") {
            chosen = 0;
        } else if((chosen+1) < $('li').length) {
            chosen++; 
        }
        selectImage(chosen);
        return false;
    }
    if (e.keyCode == 38) { 
        if(chosen === "") {
            chosen = 0;
        } else if(chosen > 0) {
            chosen--;            
        }
        selectImage(chosen);
        return false;
    }
});

function selectImage(whichIndex) {
    $('li:eq('+whichIndex+') a').trigger("click");
}
$("#selection a").click(function() {
    $('li').removeClass('selected'); 
    $(this).parent().addClass('selected');
});

在这个示例中,keydown 事件只是确定下一个“选择”的元素。一旦找到它,就会调用 selectImage() 函数,该函数基本上模拟鼠标单击所选元素。

单击元素(无论是用户单击,还是通过 jquery 调用的单击)将运行取消选择旧元素并选择新元素的实际逻辑。

可以在此处找到带有此工作示例的小提琴http://jsfiddle.net/DPHWZ/

于 2013-03-10T03:30:33.393 回答