2016-06-20 24 views
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> 
+0

你在項目中使用jQuery或只是純粹的JavaScript? – Matt

+0

純粹的JavaScript,是首選。 – Pegues

+0

[它似乎在拾取它](https://jsfiddle.net/gbwyath9/),正如警報顯示的那樣。到底發生了什麼問題? –

回答

-1

使用code屬性:http://codepen.io/topheman/pen/yJaGWv?editors=1001

<script type="text/javascript"> 

     document.addEventListener("keydown", function (event) { console.log(event.code, event.ctrlKey); }); 

     function buttonClick() { 
      var e = new KeyboardEvent("keydown", { 'ctrlKey': true, 'which': 83, 'code': 83 }); 
      document.dispatchEvent(e); 
     } 
</script> 
<form id="form1" runat="server"> 
    <div> 
    <button ID="Button1" onclick="buttonClick();">Test</button> 
    </div> 
</form> 
+0

中顯示'keydown'事件你能解釋一下你的答案嗎?爲什麼使用'code'? – Pegues