user-select CSS 属性用于控制用户是否可以选择文本。这不会对作为浏览器用户界面(即 {{Glossary("Chrome", "chrome")}})的一部分的内容加载产生任何影响,除非是在文本框中。
{{InteractiveExample("CSS Demo: user-select")}}
```css interactive-example-choice user-select: none;
```css interactive-example-choice
user-select: text;
```css interactive-example-choice user-select: all;
```html interactive-example
<section id="default-example">
<p id="example-element">Try to select this text</p>
</section>
```css interactive-example
example-element {
font-size: 1.5rem; }
## 语法
```css
/* 关键字值 */
user-select: none;
user-select: auto;
user-select: text;
user-select: contain;
user-select: all;
/* 全局值 */
user-select: inherit;
user-select: initial;
user-select: revert;
user-select: revert-layer;
user-select: unset;
[!NOTE]
user-select不是继承属性,即使默认的属性值auto的表现基本上以继承为主,似乎是继承属性。甚至,WebKit/基于 Chromium 的浏览器在实现此属性时将其作为继承属性,但这和有关规范是相悖的,且会带来一些问题。目前,Chromium 暂时选择修复将其作为继承属性所带来的问题,使最终表现符合规范。
取值
none- : 元素及其子元素的文本不可选中。请注意,
Selection对象可以包含这些元素。
- : 元素及其子元素的文本不可选中。请注意,
auto- :
auto的具体取值取决于一系列条件,具体如下: - 在
::before和::after伪元素上,采用的属性值是none - 如果元素是可编辑元素,则采用的属性值是
contain - 否则,如果此元素的父元素的
user-select采用的属性值为all,则该元素采用的属性值也为all - 否则,如果此元素的父元素的
user-select采用的属性值为none,则该元素采用的属性值也为none - 否则,采用的属性值为
text
- :
text- : 用户可以选择文本。
all- : 在一个 HTML 编辑器中,当双击子元素或者上下文时,那么包含该子元素的最顶层元素也会被选中。
contain- : 允许在元素内选择;但是,选区将被限制在该元素的边界之内。
[!NOTE] CSS UI 4 将
element值重命名为contain。
形式定义
{{CSSInfo}}
形式语法
{{csssyntax}}
示例
HTML
<p>你应该可以选中这段文本。</p>
<p class="unselectable">嘿嘿,你不能选中这段文本!</p>
<p class="all">点击一次就会选中这段文本。</p>
CSS
.unselectable {
-webkit-user-select: none; /* Safari */
user-select: none;
}
.all {
-webkit-user-select: all;
user-select: all;
}
结果
{{EmbedLiveSample("示例")}}