0
我創建了一個KeyboardEvent
,其中ctrlKey
設置爲true並且代碼爲S鍵,然後嘗試運行document.dispatchEvent(e)
以嘗試模擬ctrl + S
快捷方式,但事件偵聽器沒有似乎選擇了這一點。有另一種方法來模擬這個事件嗎?如何在JavaScript中模擬點擊事件
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
document.addEventListener("keydown", function (event) { console.log(event.which); });
onkeydown = function (e) {
if (e.ctrlKey && (e.which == 'S'.charCodeAt(0) || e.which == 's'.charCodeAt(0))) {
e.preventDefault();
alert("CTRL + S was pressed")
}
}
function buttonClick() {
var e = new KeyboardEvent("event", { 'ctrlKey': true, 'which': 83 });
document.dispatchEvent(e);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<button ID="Button1" onclick="buttonClick();">Test</button>
</div>
</form>
</body>
</html>
你在項目中使用jQuery或只是純粹的JavaScript? – Matt
純粹的JavaScript,是首選。 – Pegues
[它似乎在拾取它](https://jsfiddle.net/gbwyath9/),正如警報顯示的那樣。到底發生了什麼問題? –