我该如何编写一个onclick处理程序,在单击时执行一项操作,而在按住Shift键点击时执行另一项操作?
我该如何编写一个onclick处理程序,在单击时执行一项操作,而在按住Shift键点击时执行另一项操作?
您可以查看点击事件的shiftKey属性。
window.addEventListener("click",
function(e) {
if (e.shiftKey) console.log("Shift, yay!");
},
false);
<p>Click in here somewhere, then shift-click.</p>
您需要确保将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>
shiftKey
(或等效)属性,指示事件被触发时Shift键的状态;例如,请参见https://developer.mozilla.org/zh-CN/docs/Web/API/KeyboardEvent/shiftKey。