开发者

on e.keycode == 9 (tab), add 12 spaces, and prevent default behavior

Have a slight problem with this code :

jQuery.fn.markCursor = function(e){
    $(this).focus();
   $(this).keyup(function(e) {
  $cursorStart.enterText(e);

});

};

jQuery.fn.enterText = function(e){

if (e.keyCode == 9){
    $cursor.val("");
    alert("hello");
}

};

The tab key is resorting to its default behavior in the browser, would .preventdefault help here? How would I add 12 spaces without the code taking up 12 lines in jque开发者_运维技巧ry :p


To catch the tab keypress, you would have to bind to the keydown event. When pressing tab, a keyup event is not triggered.


e.preventDefault() would help. If you want to add twelfe spaces without literally typing them, use Array(12).join(" ");. Surely, typing twelfe spaces may be easier.

Some methods to type twelfe spaces:

var s=[];s.length=12;s.join(" ");
var s=Array(12).join(" ");
var s="            "; //Shortest so far.

As you can see, using Array(i).join(" ") starts being useful when i is higher than 17. Note that the this approach enables a dynamic indenting feature.

EDIT
Quick tuturial on key events:

  • keydown - Initiated when the key is pressed down. This event is fired once, before any default event has occured
  • keypress - This event is fired (multiple times) while the key is pressed down, before a default event has occured.
  • keyup - Fired after the key has been released (which happens only once per set of key events). Needless to say, all of the default events have already been occured.

keydown and keypress can be used to capture and cancel key events. If you want to catch and validate all key events, use keypress. If you've assigned multiple events (eg to window and to input), you may also use e.stopPropagation() in conjunction with e.preventDefault(). The first function stops the event from bubbling further (=the event isn't passed to other event listeners any more). The second function prevents the default behaviour from occuring.


I'm so sick of the overuse of Jquery. If you look at the preventDefault function, all it does is change the return value of window.event.

function stopTab(e){
    e=e||window.event;
    if(e.keyCode==9){
        document.querySelector('textarea').value+='            ';
        e.returnValue= false;
    }

}

You'll have to do something about the appending space problem by finding the cursor's position.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜