Home > Article > Web Front-end > How to Prevent Text Selection in HTML Labels?
When creating a webpage, you may encounter the need to add labels that are unselectable by default. This can be particularly useful for buttons or navigation elements where you don't want the text to be copied or highlighted.
For modern browsers that support CSS3, you can employ the following styles:
.unselectable { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; }
Apply this class to the label element:
<label class="unselectable">Unselectable Label</label>
For older browsers that lack CSS3 support, you can use JavaScript to disable text selection:
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; }; } } disableSelection(document.querySelector("label"));
This JavaScript function iterates through all labels on the page and applies the appropriate event handlers to disable selection.
If you're using jQuery, you can extend the jQuery library with the following code:
$.fn.disableSelection = function() { this.each(function() { disableSelection(this); }); };
Then, you can disable selection on all labels like so:
$("label").disableSelection();
The above is the detailed content of How to Prevent Text Selection in HTML Labels?. For more information, please follow other related articles on the PHP Chinese website!