jQuery有选择性的禁止文本选中

快乐打工仔 分类:实例代码

使用css可以实现指定元素的中的文本禁止选中效果,具体可以参阅CSS3实现的禁止文本选中代码实例一章节。

但是纯CSS方式设置不够灵活,如果能够封装成一个函数,并且能够方便的指定哪些元素中的文本不可以被选中。

代码实例如下:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<meta name="author" content="http://www.pipipi.net/" /> 
<title>前端教程网</title> 
<style type="text/css">
html,body{height:100%}
div{
  width:150px;
  height:50px;
  background:#CCC;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript"> 
$(document).ready(function(){
  (function($){
    $.fn.disableSelection=function(){
      return this.attr('unselectable','on')
      .css({'-moz-user-select':'-moz-none',
        '-moz-user-select':'none',
        '-o-user-select':'none',
        '-khtml-user-select':'none',
        '-webkit-user-select':'none',
        '-ms-user-select':'none',
        'user-select':'none'})
      .bind('selectstart', false);
    };
  })(jQuery);
  $(':not(input,select,textarea)').disableSelection();
})
</script> 
</head> 
<body>
<div id="thediv">前端教程网</div> 
<textarea></textarea>
</body> 
</html>

回复

我来回复
  • 暂无回复内容