我一直在尝试更改 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(); };