2011-09-26 106 views
1

我有这样的代码:问题移动输入到右箭头键右侧用jQuery

jQuery.fn.enterText = function(e){ 
var $cursor = $("#cursor"); 

if (e.keyCode == 39){ 
    e.preventDefault(); 
    $cursor.val(""); 
var nextChar = $cursor.next(); 
    $cursor.after(nextChar); 
} 

}; 

我试着给#cursor向右移动,但它似乎在浏览器不允许它....左箭头键的作用:

if (e.keyCode == 37){ 
    $cursor.val(""); 
var previousChar = $cursor.prev(); 
    $cursor.after(previousChar); 

} 
+1

你可以在http://jsfiddle.net上做一个演示,这样我们就可以看到你看到了什么? – Neal

+0

[jQuery caret定位](http://www.google.com/#q=jquery+caret+positioning) – Mottie

回答

0

您应该使用before代替后:

http://jsfiddle.net/Gq5HZ/1/

if (e.keyCode == 39) { 
    $cursor.val(""); 
    var nextChar = $cursor.next(); 
    $cursor.before(nextChar); 
} 

您正试图添加光标后面的元素,在光标后面...它是人造的准备好了。

0

左箭头键的作品,因为你使用after(),所以你实际上光标元素后移动前一个字符。

我会建议使用insertBefore()insertAfter(),而不是将光标移动元素,使你的意图是清晰的:

if (e.keyCode == 39) { 
    e.preventDefault(); 
    $cursor.val(""); 
    var nextChar = $cursor.next(); 
    $cursor.insertAfter(nextChar); 
} 

if (e.keyCode == 37) { 
    e.preventDefault(); 
    $cursor.val(""); 
    var previousChar = $cursor.prev(); 
    $cursor.insertBefore(previousChar); 
} 
相关问题