最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Stop cursor movement when using up and down arrow - Stack Overflow

programmeradmin5浏览0评论

I have a live search input that shows results and lets you use the up and down arrows when the results popup but I want to prevent the cursor from moving left or right when using the up and down arrows. I cannot figure this out. I tried e.preventDefault() with no luck. Here is what I have tried:

    if(e.which == 40){

        e.preventDefault();

        current = results.find('li.hover');
        current.removeClass();
        var next = current.next('li');

        if(next.length == 0){
            next = current.parent().parent().parent().next().find('li:first');

            /* Go back to the top */
            if(next.length == 0){
                next = results.find('li:first');
            }
        }

        next.addClass('hover');
        return false;
    }

Thanks!

I have a live search input that shows results and lets you use the up and down arrows when the results popup but I want to prevent the cursor from moving left or right when using the up and down arrows. I cannot figure this out. I tried e.preventDefault() with no luck. Here is what I have tried:

    if(e.which == 40){

        e.preventDefault();

        current = results.find('li.hover');
        current.removeClass();
        var next = current.next('li');

        if(next.length == 0){
            next = current.parent().parent().parent().next().find('li:first');

            /* Go back to the top */
            if(next.length == 0){
                next = results.find('li:first');
            }
        }

        next.addClass('hover');
        return false;
    }

Thanks!

Share Improve this question asked Nov 12, 2011 at 23:00 mikelbringmikelbring 1,4922 gold badges14 silver badges24 bronze badges 1
  • 1 As an aside, try using .closest() (ref) instead of multiple .parent() functions - just to keep things more readable ;) – Mottie Commented Nov 12, 2011 at 23:15
Add a ment  | 

2 Answers 2

Reset to default 17

Are you binding this onkeyup or keydown? If you are using keydown, you can prevent it, if your using keyup, the event already happened. Otherwise e.preventDefault() should be working.

You could do something like...

$('#content').on('keydown', function(event) {
    var key = event.originalEvent.key;
    if (key == 'ArrowDown' || key == 'ArrowUp') {
        event.preventDefault();
    }
});

$('#content').on('keyup', function(event) {
    // do stuff
});
发布评论

评论列表(0)

  1. 暂无评论