Html text using javascript is not optional
How can I use JavaScript to make the text in html not optional? The first method is to use the css selector as follows:
-webkit-touch-callout: none;-webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;
But this is not compatible with the old browser, so this article will discuss how to use js to implement and be compatible with all browsers.
The first thing that comes to mind is:
SO question 2310734 <script> window.onload = function() { var labels = document.getElementsByTagName('label'); for (var i = 0; i < labels.length; i++) { disableSelection(labels[i]); } }; 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; }; } } </script> Try to select this
In this way, html text is not optional. If you are using jQuery, you can also extend the JQuery plug-in to implement it:
SO question 2310734 with jQuery <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> $.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; }; } }); } }); $(document).ready(function() { $('label').disableSelection(); }); </script> Try to select this
Or:
(function ($) {$.fn.disableSelection = function () { return 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; }; } });};})(jQuery);$(document).ready(function() { $('label').disableSelection(); // Or to make everything unselectable $('*').disableSelection();});
Okay, so that it can be basically compatible with all browsers.