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
Release: 2024-12-29 13:20:10
Original
506 people have browsed it

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

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

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

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!

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