How to Render Unselectable HTML Text: A Detailed Explanation
The question arises: how to make text on a webpage unselectable, preventing the cursor from changing to a text-selecting cursor upon hovering. This behavior is typically observed on buttons, such as those found on the Stack Overflow website.
CSS3 Solution
For modern browsers, a CSS3 solution suffices:
.unselectable { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; }
To apply this style, add the unselectable class to the label element:
<label class="unselectable">Unselectable label</label>
JavaScript Fallback
For older browsers, a JavaScript fallback is necessary:
function disableSelection(element) { if (typeof element.onselectstart != 'undefined') { element.onselectstart = function() { return false; }; } else if (typeof element.style.MozUserSelect != 'undefined') { element.style.MozUserSelect = 'none'; } else { element.onmousedown = function() { return false; }; } } window.onload = function() { var labels = document.getElementsByTagName('label'); for (var i = 0; i < labels.length; i++) { disableSelection(labels[i]); } };
jQuery Solution
If jQuery is used, extend the disableSelection() function:
$.fn.extend({ disableSelection: function() { this.each(function() { if (typeof this.onselectstart != 'undefined') { this.onselectstart = function() { return false; }; } else if (typeof this.style.MozUserSelect != 'undefined') { this.style.MozUserSelect = 'none'; } else { this.onmousedown = function() { return false; }; } }); } });
Then apply it to label elements:
$(document).ready(function() { $('label').disableSelection(); });
The above is the detailed content of How to Make Text Unselectable in HTML?. For more information, please follow other related articles on the PHP Chinese website!