當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


HTML DOM Style userSelect屬性用法及代碼示例

HTML DOM 樣式的 userSelect 屬性返回並修改用戶是否可以在 HTML 文檔中選擇元素的文本。

用法

以下是語法 -

  • 返回用戶選擇

object.style.userSelect
  • 修改用戶選擇

object.style.userSelect = “value”

在這裏,價值可以是 -

解釋
auto它允許用戶根據瀏覽器設置選擇文本。
none它不允許用戶選擇文本。
text用戶可以在其中選擇文本。
all它允許通過單擊而不是雙擊來選擇文本。

示例

讓我們看一個 HTML DOM 樣式 userSelect 屬性的例子 -

<!DOCTYPE html>
<html>
<head>
<style>
   body {
      color:#000;
      background:lightblue;
      height:100vh;
   }
   .btn {
      background:#db133a;
      border:none;
      height:2rem;
      border-radius:2px;
      width:40%;
      display:block;
      color:#fff;
      outline:none;
      cursor:pointer;
   }
   .show {
      margin:1rem 0;
   }
</style>
</head>
<body>
<h1>DOM Style userSelect Property Example</h1>
<p style="direction:ltr">This is a paragraph element with some dummy text.</p>
<button onclick="add()" class="btn">Set userSelect</button>
<div class="show"></div>
<script>
   function add() {
      document.querySelector('p').style.userSelect = "none";
      document.querySelector('.show').innerHTML = "Now you can't select the above paragraph text";
   }
</script>
</body>
</html>

輸出

這將產生以下輸出 -

點擊 ”Set userSelect” 按鈕將 userSelect 設置為 none 作為段落元素的值。

相關用法


注:本文由純淨天空篩選整理自AmitDiwan大神的英文原創作品 HTML DOM Style userSelect Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。