js如何实现选中文本后点击按钮变色
就像csdn发帖的一样
选中文本,然后点击相应的颜色按钮
选中的文本就会变成相应的颜色
怎么实现啊?
js或者jquery都可以.
document.selection.createRange().text="<font color='red'>不可以</font>"
这样不行.
不要复文本编辑器.
因为项目要控制文本在表格里输入的.
阿日前哦富文本功能太多了.我只要一个变色功能.
------解决方案--------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>New Document</TITLE><script language="javascript">
function addColor() {
document.getElementById("test").style.color = "red";
}
</script>
</HEAD>
<BODY >
<table ><tbody id="listTab"></tbody>
</table>
<table>
<tr>
<td> <input name="" type="button" onClick="addColor();" value="点击"></td>
</tr>
</table>
<div id="test">hahhaha</div>
</BODY>
</HTML>------解决方案--------------------
1楼完全没有做到
首先选中文本,再次是处理选中的文本(不是一个text或者textarea哦)
我也想知道在没有兼容问题的情况下如何实现这个的。等待高人
------解决方案--------------------
帮顶!
------解决方案--------------------
抱歉看错了,呵呵....
------解决方案--------------------
HTML code<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><html><head> <title>new document</title> <script type="text/javascript"> function setColor(){ if(document.all){ var tr = document.selection.createRange(); tr.execCommand("ForeColor", false, "#FF0000"); }else{ var tr = window.getSelection().getRangeAt(0); var span = document.createElement("span"); span.style.cssText = "color:#ff0000"; tr.surroundContents(span); } } </script></head><body><div>fdjlksafjd;slafjd;slakfjds</div><input type="button" onclick="setColor()" value="setColor" /></body></html>
------解决方案--------------------
解决了,使用
document.execCommand("ForeColor", true, "#BBDDCC");
------解决方案--------------------
JScript code<select name="" id="btn"> <option value="red">红色</option> <option value="yellow">黄色</option></select><textarea id="put"></textarea><div id="display"></div><script>var t = document.getElementById('put');var btn = document.getElementById('btn').options;btn.onclick = function(){ var color = this.value ; if(window.getSelection) { if( (t.selectionStart != undefined) && (t.selectionEnd != undefined) ) { var text = t.value.substring(t.selectionStart, t.selectionEnd); alert(text); //document.getElementById('display').innerHTML = text ; //document.getElementById('display').style.color = color ; } else { return ""; } } else { var text = document.selection.createRange().text ; document.getElementById('display').innerHTML = text ; document.getElementById('display').style.color = color ; }}</script>