LoginSignup
6
4

More than 1 year has passed since last update.

【JS】Ctrl(Command)キー押しながらクリックされたかどうか判定する

Last updated at Posted at 2021-05-21

Ctrl(Command)キークリックかどうか判定したい

clickイベント時に生成される MouseEventctrlKeymetaKey を使って判定します。

例として、通常クリック時はインクリメント、Ctrl(Command) + クリック時はデクリメントするカウンターを実装してみます。
ReactとVanilaJSの2パターン実装してみました。

React

React(17.0.2)
const Button: React.FC = () => {
  const [count, setCount] = React.useState(0)

  const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
    if ((e.ctrlKey && !e.metaKey) || (!e.ctrlKey && e.metaKey)) {
      setCount(count - 1)
    } else {
      setCount(count + 1)
    }
  }

  return (
    <>
      <button onClick={handleClick}>
        クリックでインクリメント、Ctrl+クリックでデクリメント
      </button>

      <div>
        <span>カウント: </span><span>{count}</span>
      </div>
    </>
  )
}

See the Pen Ctrl+クリックでデクリメント(React) by mishiwata1015 (@mishiwata1015) on CodePen.

素朴なHTML + JS

HTML
<button id="button">
  クリックでインクリメント、Ctrl+クリックでデクリメント
</button>

<div>
  <span>カウント: </span><span id="count">0</span>
</div>
JS
let count = 0

document.getElementById('button').onclick = function handleClick(e) {
  if ((e.ctrlKey && !e.metaKey) || (!e.ctrlKey && e.metaKey)) {
    count--
  } else {
    count++
  }

  document.getElementById('count').textContent = count
}

See the Pen Ctrl+クリックでデクリメント(VanilaJS) by mishiwata1015 (@mishiwata1015) on CodePen.

MouseEvent.ctrlKey

Ctrlキーが押されてたどうか取得できます。

読み取り専用プロパティ MouseEvent.ctrlKey は、イベント発生時に control キーが押されたかどうかを、押されていた (true) または押されていない (false) のBoolean で返します。

そのまんまですね。

MouseEvent.metaKey

メタキーが押されていたかどうか取得できます。
どのキーがメタキーに該当するかは環境に依存します。

On Macintosh keyboards, this key is the command key (⌘). On Windows keyboards, this key is the Windows key (⊞).

つまり、Windowsの場合はWindowsキー(⊞)、Macの場合はCommandキー(⌘)が押されていたかどうか取得できます。

まとめ

MouseEvent.ctrlKeyMouseEvent.metaKey を使って以下のように判定することで、Ctrl(Command)キー押しながらクリックされたかどうか判定できます。

  • Windows用: ctrlKey: true && metaKey: false
  • Mac用: ctrlKey: false && metaKey: true

ちなみに、↑のコードはMacで動くことは確認しましたが、Windowsでは動作確認できてないです。
どなたか動くかどうか教えてもらえると助かります :bow:

参考

6
4
0

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
6
4