Home > Web Front-end > CSS Tutorial > How to Highlight Selected Text with a Background Color Using JavaScript?

How to Highlight Selected Text with a Background Color Using JavaScript?

DDD
Release: 2024-11-16 13:27:03
Original
1009 people have browsed it

How to Highlight Selected Text with a Background Color Using JavaScript?

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 &amp;&amp; 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";
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template