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!