我一直在努力改变textarea的中突出显示的内容颜色玩耍,但看起来你不能改变textarea文本的颜色。如前所述,另一种方法是创建一个可编辑的div,充当丰富的文本框。您可以将div上的contentEditable属性设置为true,以使其工作。这是我的jsfiddle,如果你想玩它。
这里是我的JS代码。我也在HTML上更改了一些东西,所以请查看完整代码的jsfiddle。
function GetSelectedText (origtext, seltext, tcolor) {
//alert(origtext + ", " + seltext + ", " + tcolor);
var divcontent = document.getElementById('sec');
var spanTag = document.createElement("span");
var selIndex = origtext.indexOf(seltext);
var selLength = seltext.length;
//split the text to insert a span with a new color
var fpart = origtext.substr(0, selIndex);
var spart = origtext.substr(selIndex + selLength);
//alert(fpart + ", " + spart);
// add the text that was highlighted and set the color
spanTag.appendChild(document.createTextNode(seltext));
spanTag.style.color = tcolor;
//remove all the children of the div
while(divcontent.hasChildNodes()){
divcontent.removeChild(divcontent.lastChild);
}
//append the original text with the highlighted part
divcontent.appendChild(document.createTextNode(fpart));
divcontent.appendChild(spanTag);
divcontent.appendChild(document.createTextNode(spart));
}
// this function was found at http://stackoverflow.com/questions/275761/how-to-get-selected-text-from-textbox-control-with-javascript
function getTextFieldSelection() {
var textComponent = document.getElementById('content');
var selectElem = document.getElementById("myselect");
var selectedText;
// IE version
if (document.selection != undefined)
{
textComponent.focus();
var sel = document.selection.createRange();
selectedText = sel.text;
}
// Mozilla version
else if (textComponent.selectionStart != undefined)
{
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos)
}
//alert("You selected: " + selectedText);
selectElem.onchange = GetSelectedText(textComponent.value, selectedText,selectElem.options[selectElem.selectedIndex].text.toLowerCase());
}
var content = document.getElementById("content");
var selectElem = document.getElementById("myselect");
selectElem.onfocus = function (e) { getTextFieldSelection(); };