使用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>
<!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
- 使用javascript实现html文本不可选
- 使用javascript实现html文本不可选
- 实现html中select下拉列表中部分选项不可选
- Html 滚动文字不使用Javascript应用
- javascript调用TTS实现语音播报html文本信息
- html checkbox 复选框 enabled disabled 不可选
- html中select下拉列表中部分选项不可选(
- TextView文本可选中
- CSS3 不使用javascript 实现click
- javascript实现checkbox,多选 : 最多可选 2 项
- option 变为不可选
- Ztree 节点不可选
- input等不可选
- html原样输出文本不转义
- HTML中的文本段落实现
- 使用javaxmail发送邮件(带/不带附件,文本邮件/html邮件)
- 不使用后台,直接使用JavaScript实现检索功能
- 使用UITextView加载html文本
- android sdk——listView的用法
- ORA-39700:DATABASE MUST BE OPENED WITH UPGRADE OPTION
- 户外广告4A公司动向
- Android数据库安全解决方案,使用SQLCipher进行加解密
- 中国互联网的十一种盈利模式
- 使用javascript实现html文本不可选
- 佛祖保佑 永无bug
- 户外广告要创意但也不能毁三观
- 在Sql2000 sql2005 sql2008 下已能实现事务复制的强制订阅,但请求订阅始终不能实现总有下列错误提示
- 2014-7-20 谁还认得这几本书?
- VS2008 编译SQLite 3.8.4.3 + sqlcipher-3.1.0 + openssl-1.0.1g
- 2013年户外广告发展格局和趋势
- 创意开启户外广告文化意义
- HDU 2602 Bone Collector(01背包经典)