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

42

我该如何编写一个onclick处理程序,在单击时执行一项操作,而在按住Shift键点击时执行另一项操作?

3个回答

74

您可以查看点击事件的shiftKey属性。

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


7

您需要确保将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>

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接