开发者

moving an appended input after clicked span.

Im working on a text editor simulation that appends an input to a div, and extracts its values to create spans, here is the initial click() function:

var $cursorStart= $("#cursor-start");

$("#main-edit").click( function() {
var cursorExists = $("#cursor").length;
if (!cursorExists){
   $cursorStart.append("<input type='text' id = 'cursor' />");
   $("#cursor").markCursor();

}
   if (cursorExists){
    $("#cursor").focus();

}

});

When I start typing, spans are inserted before the input:

jQuery.fn.enterText = function(e){
var $cursor = $("#cursor");
if( $cursor.val() && e.keyCode != 32  ){
    var character = $("#cursor").val();
    $cursor.val("");
    character = character.split("").join("</span><span class='text'>");
    $("<span class = 'text'>"+character+"</span>").insertBefore($cursor);



}

What I want to know now is, how can I move the input (cursor) around (basically be inserted after a clicked span).

<span>a</span>
<span>b</span>
<span>c</span>
<span>d</span>

clicking near a and b would result in 开发者_如何学Can input after "a". These are spans that are dynamically added.


After adding the new span, you can bind a new click event to it:

$("<span class = 'text'>"+character+"</span>").insertBefore($cursor);

$cursor.prev().click(function(){
  $(this).after($cursor);
});

You could also use jQuery's .live() function, but this is generally not a good solution because it is so expensive.


Check out jQuery caret plugin for x-browser compatible functions for managing the caret position or selection in a textbox or textarea. This will allow you to move the "input cursor" around, as you described it :-)


This is assuming "What I want to know now is, how can I move the input (cursor) around" was your question, which I'm not 100% clear on.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜