User-select详解:控制文字选中

发布时间:2023-05-23

一、user-select怎么样

user-select属性控制是否允许用户选择文本,以及如何选择文本。该属性在CSS3中出现。 如果user-select的值被设置为none,则所有子元素都无法选中文本。而如果值设置为auto,则子元素将跟随父元素的规则。 对于需要禁止用户选中的元素,如代码框或工具提示,可以使用user-select:none(注意,这可能仅适用于WebKit浏览器)。

二、user-select的默认行为

默认情况下,user-select是对文本上的鼠标光标进行的选择。 下面的代码段演示了如何使用CSS3 user-select属性 来控制文字的选中:

* {
    user-select: none;
}

三、user-select的skip属性

skip属性指定哪些元素不应影响或限制其父级及其祖先元素的user-select属性。其可选值为none和all。 例如,当某一行包含一些文本和一个字体图标时,我们不希望用户在文本和图标之间选择:

.no-user-select, .no-user-select * {
    -webkit-user-select: none; /* Chrome all / Safari all */
    -moz-user-select: none;
    -ms-user-select: none; /* IE 10+ */
    user-select: none; /* Likely future */ 
}

四、user-select的selected属性

selected属性允许用户选中文本,但文字看起来不同。我们可以使用JavaScript和CSS组合来显示放缩的文本,例如放大的文本,而不是选择内容。下面是一段CSS代码,使用了user-select来隐藏一部分内联CSS,以使放大的文本仍然可见:

#custom-selection {
  /* Define an invisible character */
  font-size: 16px;
  color: rgba(0, 0, 0, 0);
  user-select: none;
  display: inline-block;
  width: 0;
  height: 2em;
}
#custom-selection::before {
  /* Display a "normal" character */
  content: '\221A';
  font-size: 32px;
  color: black;
  display: inline-block;
  margin-right: 10px;
  /* No user selection here */
  user-select:none;
}
#custom-selection::after {
  /* Display your magnified text here */
  content: 'This text is awesome';
  color: red;
  display: inline-block;
  /* Your style rules here */
  font-size: 48px;
  font-weight: bold;
  background-color: yellow;
  /* No user selection here */
  user-select:none;
}

五、user-select为none的input框不对选取

当设置input元素的user-select为none时,文字不会被选择,但使用鼠标拖动仍然可以滚动文本。此时需要通过CSS将文本框禁用掉:

input[type="text"] {
  pointer-events: none;
  user-select: none;
  opacity: .5;
}

此时,input框将不会影响到鼠标的取词和选中文本,同时,此输入框将呈现为禁用状态。