Changing the CSS of Selected Text Using JavaScript
To highlight selected text on a webpage, you can use the execCommand() function, which allows you to change the background color in modern browsers.
To achieve this, you can use the following function:
function highlight(colour) { var range, sel; if (window.getSelection) { // IE9 and non-IE try { if (!document.execCommand("BackColor", false, colour)) { makeEditableAndHighlight(colour); } } catch (ex) { makeEditableAndHighlight(colour) } } else if (document.selection && document.selection.createRange) { // IE <= 8 case range = document.selection.createRange(); range.execCommand("BackColor", false, colour); } } function makeEditableAndHighlight(colour) { var range, sel = window.getSelection(); if (sel.rangeCount && sel.getRangeAt) { range = sel.getRangeAt(0); } document.designMode = "on"; if (range) { sel.removeAllRanges(); sel.addRange(range); } // Use HiliteColor since some browsers apply BackColor to the whole block if (!document.execCommand("HiliteColor", false, colour)) { document.execCommand("BackColor", false, colour); } document.designMode = "off"; }
This function checks for the selection range and applies the specified background color using execCommand(). It handles both IE and non-IE browsers, ensuring cross-browser compatibility.
The above is the detailed content of How to Highlight Selected Text with a Background Color Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!