[英]If text is selected, and dropdown option is clicked, change color of selected text
我想創建一個文本編輯器,當您在文本區域中選擇一些文本,然后從下拉菜單中單擊一個選項時,從文本區域中選擇的文本將更改顏色。 不幸的是,我不知道該怎么做,因為當我嘗試訪問下拉菜單時,從文本區域中選擇的內容就會消失。
jsFiddle :: http://jsfiddle.net/MatthewKosloski/a77sM/
function GetSelectedText () {
if (window.getSelection) { // all browsers, except IE before version 9
var range = window.getSelection ();
var selection = range.toString();
alert(selection);
}
}
問題是,當您單擊選擇元素時,它會從文本區域竊取焦點。 您必須將焦點返回給textarea元素,這是一個有效的示例(至少在chrome中):
var color = document.getElementById("color"), // this is the select element
content = document.getElementById("content");
color.onfocus = function (){ content.focus(); };
我一直在嘗試更改文本區域內突出顯示的內容的顏色,但是似乎您無法更改文本區域內的文本顏色。 如之前所建議的,另一種方法是創建一個可編輯的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(); };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.