CSS user-select (用户选择)属性确定用户是否可以选择文本,而不会影响作为浏览器用户界面 (chrome) 的一部分加载的内容(文本框除外)。
虽然 user-select 不是继承的,但其初始的“auto”值通常使其行为就像是继承的一样。基于 WebKit/Chromium 的浏览器将属性实现为继承的属性,这违反了规范并会导致问题。Chromium 一直在解决这些问题,以符合指定的行为。可能的值
- none − 元素和子元素的文本不可选择,但这些元素可能存在于 Selection 对象中。
- auto − auto 值的确定方式如下:
- 用于 ::before 和 ::after 伪元素的值为 none。
- 对于可编辑元素,使用的值为 contain。
- 如果此元素的父元素具有用户选择值 all,则使用的值为 all。
- 如果此元素的父元素具有用户选择值 none,则使用的值为 none。
- 使用的值是文本。
- text - 用户可以选择文本。
- contain − 允许在元素内开始选择,但包含到该元素边界的选择。
- all − 必须以原子方式选择元素的内容:如果选择包含元素的一部分,则它还必须包含其所有后代。如果在子元素中发生双击或上下文单击,则将选择具有此值的最高祖先。
适用于
所有元素。
语法
user-select: none | auto | text | contain | all;
CSS user-select - none 值
以下示例演示了 user-select:none 属性阻止用户选择文本 -
<html>
<head>
<style>
.text-none {
-webkit-user-select: none;
user-select: none;
}
</style>
</head>
<body>
<p>This text should be selectable.</p>
<p class="text-none">This text cannot be selected.</p>
</body>
</html>
CSS user-select - auto 值
以下示例演示了用于选择文本的 user-select:auto 属性 -
<html>
<head>
<style>
p {
-webkit-user-select: auto;
user-select: auto;
}
</style>
</head>
<body>
<p>This text should be selectable.</p>
</body>
</html>
CSS user-select - text 值
以下示例演示了 user-select:text 属性允许用户选择文本 -
<html>
<head>
<style>
p {
-webkit-user-select: text;
user-select: text;
}
</style>
</head>
<body>
<p>This text should be selectable.</p>
</body>
</html>
CSS user-select - all 值
以下示例演示了 user-select:all 属性允许用户在单击中选择文本 -
<html>
<head>
<style>
p {
-webkit-user-select: all;
user-select: all;
}
</style>
</head>
<body>
<p>This text can be selected with a single click.</p>
</body>
</html>
CSS user-select - contain 值
以下示例演示了 user-select:contain 属性允许用户在段落的边界内选择文本 -
<html>
<head>
<style>
p {
-webkit-user-select: contain;
user-select: contain;
}
</style>
</head>
<body>
<p>This text can be selected within the paragraph's boundaries.</p>
</body>
</html>