日期:2014-05-16 浏览次数:20379 次
<style>
#editor{border:solid 1px #000;height:150px;width:300px;}
</style>
<div id="editor" contenteditable="true">测试内容</div>
<input type="button" value="红色" onclick="Color('red')" />
<script>
function Color(c) {
var e = document.getElementById('editor');
e.focus();
if (window.getSelection) {
var s = window.getSelection(), r = s.getRangeAt(0);
if (r.toString() == '') { alert('请选择内容!'); return }
var sp = document.createElement('span');
sp.style.color = c;
r.surroundContents(sp);
s.collapse(sp, 1);
}
else if (document.selection) {
var r = document.selection.createRange();
r.pasteHTML('<span style="color:' + c + '">' + r.text + '</span>');
}
}
</script>