我需要将空格和新行转换为<“br /”>和& nbsp。使用相同的格式将文本从TEXTAREA转换为DIV - 并使用相同的格式将onClick转换回TEXTAREA。怎么做?
HTML
<div id="meText"><br />Click to edit <br />this text.<br /> And this line has space   on the begining.<br />How to convert space to   ? <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(/ /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 /> ");
//newText = newText.replace(/\s\s/g," ");
$(this).replaceWith($(originalDiv).html(newText));
}));
});
});
答案 0 :(得分:6)
执行以下操作:( javascript )
var x = "div to textarea";
var y = "textarea to div";
var div = document.getElementById('myDiv');
var txt = document.getElementById('myText');
var btn = document.getElementById('myBtn');
$(btn).click(function () {
if (this.innerHTML == x) {
txt.value = div.innerHTML.split('<br>').join('\n').split(' ').join(' ');
div.innerHTML = "";
btn.innerHTML = y;
} else {
div.innerHTML = txt.value.split('\n').join('<br>').split(' ').join(' ');
txt.value = "";
btn.innerHTML = x;
}
});
我希望至少能给你一些想法。