CSS - user-select 屬性



CSS user-select 屬性確定使用者是否可以選擇文字,對作為瀏覽器使用者介面(chrome)一部分載入的內容(除了文字框以外)沒有影響。

雖然 user-select 不是繼承的,但其初始值“auto”通常使其表現得好像繼承了一樣。基於 WebKit/Chromium 的瀏覽器將該屬性實現為繼承的,這違反了規範,並且會導致問題。Chromium 已經 解決 這些問題以符合指定的行為。

可能的值

  • none − 元素及其子元素的文字不可選擇,但這些元素可能存在於 Selection 物件中。

  • auto − auto 值的確定方式如下

    • ::before::after 偽元素使用 none 值。

    • 對於可編輯元素,使用的值是 contain

    • 如果此元素的父元素具有 user-selectall,則使用的值是 all

    • 如果此元素的父元素具有 user-selectnone,則使用的值是 none

    • 使用的值是 text。

  • 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>
廣告