简体   繁体   中英

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

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

You can look at the click event's shiftKey property.

 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. 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; see, eg https://developer.mozilla.org/en/DOM/event.shiftKey for an example.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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