问题
I want to highlight feature which will change the color of the selected text using Javascript. I am using the following method.
function android_selection_highlight(replacrmenthtml){
try {
if (window.getSelection) {
sel = window.getSelection();
var range = sel.getRangeAt(0);
var selectionStart = $("<span style=\"color:red\">");
var startRange = document.createRange();
startRange.setStart(range.startContainer, range.startOffset);
var selectionEnd = $("</span>");
var endRange = document.createRange();
endRange.setStart(range.endContainer, range.endOffset);
startRange.insertNode(selectionStart[0]);
endRange.insertNode(selectionEnd[0]);
}
}
catch (e) {
}
}
But it is giving DOM exception when I am calling the method. I think that when I am inserting starting span tag in front of the selected text, it is disrupting the DOM structure as there is no end tag at that moment. How to solve this problem?
Edited: There will a highlight button. Selecting the text, if user click on the highlight button, the text color of the selected text will change.
回答1:
if on select u want to change color use this code.
::-moz-selection { color: red;}
::selection { color: red; }
回答2:
I know that this is a JS question, but there is a CSS selector which allows you to do this.
::selection {
color: red;
}
If the browser considers that you've made a choice which is not accessible, it might override your colours. Not everything can be styled in this way, but colours and background colours can.
More information:
- ::selection on CSS Tricks
- ::selection on MDN
来源:https://stackoverflow.com/questions/29845266/color-change-of-the-selected-text-in-html