LoginSignup
0
0

disabledを使わずにボタンを無効化する方法 pointer-events:noneとcursor: not-allowedを同時に使う時の注意点

Last updated at Posted at 2023-08-02

前置き

HTML
<button type="button" disabled >ボタン</button>

一般的にボタンにはdisabledを使う

この記事はこのような人向け
・ボタンに対してdisabledを使えない理由がある
・そもそもボタンではなく、aタグやdivなのでdisabledが使えない

やりたいこと

・ボタンをdisabledせずに、ユーザーのマウス操作によるイベント発火を防ぎたい
・ボタンが操作を受け付けないことを表現したい

こう書くとうまくいかない

HTML
<button type="button" class="unusable">ボタン</button>
CSS
.unusable {
    pointer-events: none;
    cursor: not-allowed; /* It doesn't Work */
}

cursor: not-allowedが機能せず、カーソルはcursor: defaultと同じ形になります

解決方法

cursor: not-allowedは親要素に付与する

HTML
<div class="btn-wrapper">
    <button type="button" class="unusable">ボタン</button>
</div>
CSS
.btn-wrapper {
    cursor: not-allowed; /* It Works! */
}
.btn-wrapper .unusable {
    pointer-events: none;
}

余談1

次の表はブラウザごとの
disabledを付与することで
マウスクリックによって発火されなくなるイベント一覧です

ブラウザ 発生しなくなるイベント
Chrome click, focus/blur
Firefox click, focus/blur, mouseup/down
Safari たくさん。詳細はソース参照
IE11,Edge 無し。対策はソース参照
iOS Safari click, focus/blur
Android Chrome click, focus/blur

↓表のソースとIE・Edge対策方法
5年前の記事なので注意。他のソースを自分は見つけられなかった。

余談2

disabledでもpointer-events:noneでも
javascript側でイベントを能動的に起こせる

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0