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

preventdefault - javascript prevent cursor to move - Stack Overflow

programmeradmin4浏览0评论

Into an input box, I want to stop the propagation of the cursor just as I type on the up key "↑" :

Before :

tes|t // cursor is before t

After :

|test // cursor went beginning

I want to prevent the cursor to move, so it has to stay before t.

So far, I'm trying with this, but it doesn't work :

$('input').keyup(function(e) {

    if (e.which == 40) { // up key
        e.stopPropagation();
        e.stopImmediatePropagation();
        e.preventDefault();

        // actions

        return false;
    }

}

Is this possible anyway ?

Into an input box, I want to stop the propagation of the cursor just as I type on the up key "↑" :

Before :

tes|t // cursor is before t

After :

|test // cursor went beginning

I want to prevent the cursor to move, so it has to stay before t.

So far, I'm trying with this, but it doesn't work :

$('input').keyup(function(e) {

    if (e.which == 40) { // up key
        e.stopPropagation();
        e.stopImmediatePropagation();
        e.preventDefault();

        // actions

        return false;
    }

}

Is this possible anyway ?

Share Improve this question asked Mar 29, 2013 at 22:35 MenenciaMenencia 1,2891 gold badge12 silver badges23 bronze badges 3
  • 2 Try keydown instead of keyup. – Fabrício Matté Commented Mar 29, 2013 at 22:37
  • 1 That's probably not a good idea. I personally rely on this behaviour when typing (albeit rarely)... – Niet the Dark Absol Commented Mar 29, 2013 at 22:37
  • 1 @FabrícioMatté: That works just great with keydown :) – Menencia Commented Mar 29, 2013 at 22:41
Add a ment  | 

1 Answer 1

Reset to default 8

You can use keydown for that:

$('input').keydown(function(e) {
    if (e.which == 40) { // up key
        return false;
    }
}

keyup fires after the keypress event has been handled and keypress is supposed to not fire for non-printable characters (though there are some inconsistencies across different browsers), so preventing the event's default action right at keydown is the best course of action.

Keep in mind that if you don't have a good reason for preventing the default action (e.g. going through an autoplete list while having the search field focused), you may be affecting other users' usability as mented by @Kolink.

发布评论

评论列表(0)

  1. 暂无评论