Home >Web Front-end >CSS Tutorial >How Can I Prevent Text Selection on My HTML Pages?

How Can I Prevent Text Selection on My HTML Pages?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-29 13:20:10520browse

How Can I Prevent Text Selection on My HTML Pages?

Preventing Text Selection on HTML Pages

Question:

To enhance the UI of an HTML page, how can text elements, like tab names, be made unselectable to avoid unintentional highlighting?

CSS/HTML Solution:

Across most browsers, the following CSS can be applied:

*.unselectable {
   -moz-user-select: -moz-none;
   -khtml-user-select: none;
   -webkit-user-select: none;

   -ms-user-select: none;
   user-select: none;
}

For elements that do not inherit this property, such as in IE < 10 and Opera, the unselectable attribute can be added directly to the desired element:

<div>

JavaScript Solution:

As a recursive alternative to manually adding the unselectable attribute to each element within a container, JavaScript can be used:

function makeUnselectable(node) {
    if (node.nodeType == 1) {
        node.setAttribute("unselectable", "on");
    }
    var child = node.firstChild;
    while (child) {
        makeUnselectable(child);
        child = child.nextSibling;
    }
}

makeUnselectable(document.getElementById("foo"));

The above is the detailed content of How Can I Prevent Text Selection on My HTML Pages?. 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