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

How Can I Prevent Text Selection on My HTML Page?

Susan Sarandon
Release: 2024-12-14 16:46:19
Original
714 people have browsed it

How Can I Prevent Text Selection on My HTML Page?

Unselecting Text on an HTML Page: A Comprehensive Guide

In the realm of user experience, it can be desirable to prevent text selection on certain elements within an HTML page. This is particularly relevant for elements like tab names, which can appear unappealing when highlighted.

CSS Solution

Fortunately, most modern browsers offer a CSS-based solution:

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

  /* IE 10+ */
  -ms-user-select: none;
  user-select: none;
}
Copy after login

Simply add this code to your stylesheet, and the designated elements will become unselectable.

IE and Opera Alternative

For earlier versions of Internet Explorer and Opera, the unselectable attribute can be used:

<div>
Copy after login

However, note that this attribute is not inherited, so you may need to explicitly set it for each descendent element.

Recursive JavaScript Solution

If you encounter inheritance issues, you can employ JavaScript to apply the unselectable attribute recursively:

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 Page?. 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