简体   繁体   English

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

[英]In an onclick handler, how can I detect whether shift was pressed?

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

You can look at the click event's shiftKey property. 您可以查看click事件的shiftKey属性。

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

You need to make sure you pass event as a parameter to your onclick function. 您需要确保将event作为参数传递给onclick函数。 You can pass other parameters as well. 您也可以传递其他参数。

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

The event fired from the DOM ought to contain a shiftKey (or equivalent) property indicating the state of the shift key when the event was fired; 从DOM触发的事件应该包含一个shiftKey (或等效)属性,指示触发事件时shift键的状态; see, eg https://developer.mozilla.org/en/DOM/event.shiftKey for an example. 例如, 参阅https://developer.mozilla.org/en/DOM/event.shiftKey

If you're using a JavaScript/DOM wrapping library such as YUI, Prototype or jQuery, any differences in implementation ought not to be an issue. 如果您正在使用诸如YUI,Prototype或jQuery之类的JavaScript / DOM包装库,那么实现中的任何差异都不应成为问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM