javascript 指定した要素の選択を不可能にする

javascript 指定した要素の選択を不可能にする

javascriptで、指定した要素の選択を不可能にするサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 104.0.5112.101

指定した要素の選択不可能に設定

指定した要素の選択を不可能にするには「onselectstart」に要素を指定して「false」を返すことで可能です。

<div>
  <p>選択可能</p>
  <p id="hoge">選択不可能</p>
  <p>選択可能</p>
</div>

<script>

'use strict';

hoge.onselectstart = function() {
 
 return false;

}

</script>

実行結果を確認すると、「id hoge」が選択不可能になっていることが確認できます。

また、以下のコードを、

hoge.onselectstart = function() {
 
 return false;

}

アロー関数を使用して、簡潔に記述することもできます。

hoge.onselectstart = () => false;

サンプルコード

以下は、
「実行」ボタンをクリックして、「id」が「foo」の要素を選択不可にするサンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>  
  
  const hoge = () => {

    foo.onselectstart = () => false;
    
  }

  window.onload = () => {

    btn.onclick = () => { hoge() };

  }

</script>

<body>
  <div class="container mx-auto my-56 w-64 px-4">

    <div id="sample" class="flex flex-col justify-center">
      <h2 id="hoge" class="font-semibold text-lg mr-auto">選択可能</h2>
      <h2 id="foo" class="font-semibold text-lg mr-auto">選択不可</h2>
      
      <button id="btn" class="mb-2 md:mb-0 bg-yellow-400 px-5 py-2 text-sm shadow-sm font-medium tracking-wider text-white rounded-full hover:shadow-lg hover:bg-yellow-500">
        実行
      </button>
    </div>

  </div>
</body>

</html>

実行結果を確認すると、選択不可になっていることが確認できます。