我知道这在技术上不是你想要的,但无论如何我都会作弊。
Javascript:
var textarea = document.getElementById('textarea');
var div = document.getElementById('holder');
var original_value = textarea.value;
textarea.onblur = function () {
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
textarea.style.display = "none";
div.innerHTML = textarea.value.splice(end, 0, "</span>").splice(start, 0, "<span>");
div.style.display = "block";
}
div.onclick = function () {
div.style.display = "none";
textarea.style.display = "block";
textarea.value = original_value;
}
String.prototype.splice = function( idx, rem, s ) {
return (this.slice(0,idx) + s + this.slice(idx + Math.abs(rem)));
};
HTML:
<p><textarea id="textarea" rows="4" cols="30">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</textarea></p>
<div id="holder"></div>
<p><input id="click" type="button" value="Click me"></p>
CSS:
textarea, #holder{
height: 120px;
width: 300px;
border: 1px solid black;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 3px;
font-size: 10pt;
font-family: Arial;
}
#holder{
display: none;
}
#holder span{
background-color: #b4d5ff;
}
演示:http: //jsfiddle.net/Mb89X/4/