在onclick处理程序中,如何检测是否按下了shift?

mik*_*ike 27 javascript

我如何编写一个onclick处理程序,为常规点击做一件事,为点击点击做另外一件事?

AKX*_*AKX 53

您可以查看click事件的shiftKey属性.

window.addEventListener("click",
  function(e) {
    if (e.shiftKey) console.log("Shift, yay!");
  },
  false);
Run Code Online (Sandbox Code Playgroud)
<p>Click in here somewhere, then shift-click.</p>
Run Code Online (Sandbox Code Playgroud)


Rya*_*yan 5

您需要确保将其event作为参数传递给onclick函数。您也可以传递其他参数。

<html>
<head>
    <script type="text/javascript">
        function doSomething(event, chkbox)
        {
            if (event.shiftKey)
                alert('Shift key was pressed while picking ' + chkbox.value);
            else
                alert('You picked ' + chkbox.value);
        }
    </script>
</head>
<body>
    <h3>Pick a Color</h3>
    <input type="radio" name="myColors" onclick="doSomething(event, this)" value="Red" /> Red<br/>
    <input type="radio" name="myColors" onclick="doSomething(event, this)" value="Green" /> Green<br/>
    <input type="radio" name="myColors" onclick="doSomething(event, this)" value="Blue" /> Blue<br/>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)