JS魔法堂:阻止元素被选中

时间:2022-04-22
本文章向大家介绍JS魔法堂:阻止元素被选中,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、前言                            

  在为IE5.5~9polyfill HTML5新特性placeholder时需要阻止元素被选中,因此在网上、书上查阅相关资料,记录在此以便日后查阅。

二、IE10+实现方式──CSS3                    

.unselect {
    -webkit-user-select: none; 
    -moz-user-select: none;    
    -khtml-user-select: none;  
    -ms-user-select: none;    

    /* 以下两个属性目前并未支持,写在这里为了减少风险 */
    -o-user-select: none;
    user-select: none;  
}

user-select: auto; => 用户可以选中元素中的内容

user-select: none; => 用户不可选中元素中的内容

user-select: text; => 用户可以选中元素中的文字

目前这个 user-select 兼容 Chrome 6+、Firefox、IE 10+、Opera 15+、Safari 3.1+。

三、IE5.5~9的实现──unselectable属性                

<span unselectable="on"></span>

由于unselectable属性不具有继承性,所以要遍历所有子元素并为各子元素添加该属性才有效。

// 将元素及其后代元素均设置为不可选择
var unselectable = function(root){
  root.setAttribute('unselectable', 'on');
  var descendant = root.getElementsByTagName("*");
  var rTagName = /input|iframe|textarea|select/i;
  for (var i = 0, el; el = descendant[i++];){
    if (!rTagName.test(el.tagName)){
      el.setAttribute('unselectable', 'on');
    }  
  }
};

四、参考                             

  《JavaScript框架设计》──9.3.2 user-select

   http://www.html-js.com/article/The-Laispace-block-element-is-selected-and-clear-the-check-method