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

How Can I Prevent Text Selection in HTML?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 05:15:10417browse

How Can I Prevent Text Selection in HTML?

Unselectable Text in HTML

Question: In an HTML UI, is it possible to prevent users from selecting specific text elements, such as tab names?

Answer:

Yes, there are several ways to make text unselectable in HTML:

Using CSS:

In modern browsers, this can be achieved with CSS using the user-select property:

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

Using the unselectable Attribute (IE and Opera):

For older versions of IE and Opera, the unselectable attribute can be applied to specific elements:

<div>

Note: This attribute is not inherited, so it must be specified for each element that should not be selectable.

Recursive Unselection with JavaScript:

Alternatively, JavaScript can be used to recursively set the unselectable attribute for all descendants of an element:

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 in HTML?. 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