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

How Can I Prevent Text Selection in HTML?

Patricia Arquette
Release: 2024-12-09 05:15:10
Original
471 people have browsed it

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

Using the unselectable Attribute (IE and Opera):

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

<div>
Copy after login

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"));
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template