Home >Web Front-end >CSS Tutorial >How to Change the Background Color of Selected Text with JavaScript?

How to Change the Background Color of Selected Text with JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-20 01:22:03888browse

How to Change the Background Color of Selected Text with JavaScript?

How to Change the CSS of Selected Text with JavaScript

In order to enhance web page functionality, you may want to create a JavaScript bookmarklet that highlights selected text, changing its background to yellow. While you can easily retrieve the text using getSelText(), you may encounter difficulties when attempting to change its CSS with jQuery's highlightSelText() function.

This issue arises because highlightSelText() isn't able to alter the CSS of the selected text. A more effective solution is to employ the execCommand() method, which provides a command to modify the background color in contemporary browsers. Here's an updated code snippet that leverages this capability:

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);
    }
}

This function takes advantage of execCommand() to apply the desired background color to the selected text, ensuring compatibility with all major browsers, including Internet Explorer.

The above is the detailed content of How to Change the Background Color of Selected Text with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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