0

スペースと改行を <"br /"> と   に変換する必要があります。テキストを TEXTAREA から DIV に同じフォーマットで変換し、onClick でテキストを同じフォーマットで TEXTAREA に変換します。どうやってするの ?

jsFiddle デモ

HTML

<div id="meText"><br />Click to edit <br />this text.<br /> And this line has space &nbsp on the begining.<br />How to convert space to &nbsp ? <br /> <br /></div>

CSS

#meText{
    margin: 20px;
    width: 300px;
    height: 200px;
    background: red;
    font-family: Arial;
    font-size: 13px;
}
textarea {
    margin: 20px;
    font-family: Arial;
    font-size: 13px;
}

jQuery

$(function(){
    $("#meText").live('click',function(){
        var originalDiv = this;
        oldText = $(this).html().replace(/<br\s?\/?>/g,"\n");
        oldText = oldText.replace(/&nbsp;/g," ");
        $(this).replaceWith($("<textarea></textarea>").text(oldText).width($(this).width()).height($(this).height()).blur(function(){
            newText = $(this).val().replace(/\r\n|\r|\n/g,"<br />");

            //newText = newText.replace(/\n\s|\r\s|\r\n\s/g,"<br />&nbsp;");
            //newText = newText.replace(/\s\s/g,"&nbsp;&nbsp;");

            $(this).replaceWith($(originalDiv).html(newText));
        }));
    });
});
4

1 に答える 1