使用javascript实现html文本不可选

来源:互联网 发布:java声明构造方法 编辑:程序博客网 时间:2024/05/21 10:57

如何使用js让html中的文本不可选呢?首先想到的方法是使用css选择器来实现,如下:

-webkit-touch-callout: none;-webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;

但是这样并不能兼容旧的浏览器,所以下本文将讨论如何使用js来实现,并兼容所有浏览器。

首先想到的是:

<!doctype html><html lang="en">    <head>        <title>SO question 2310734</title>        <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>    </head>    <body>        <label>Try to select this</label>    </body></html>


这样就可以完成html文本不可选了,如果你在使用jQuery也可以扩展JQuery插件的方式来实现:


<!doctype html><html lang="en">    <head>        <title>SO question 2310734 with jQuery</title>        <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>    </head>    <body>        <label>Try to select this</label>    </body></html>

或者:

(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();});

好的,这样就可以基本上兼容所有的浏览器了。

0 0
原创粉丝点击