向html元素發送鍵盤事件

原版的towers網頁版,如果沒有電腦鍵盤的話是玩不了的,除非你用的是priv手機。

今找到了向html元素發送鍵盤事件的方法,並為towers加上,這樣一來,觸屏手機也能玩網頁版了。

效果擷圖。

 

直接玩

主要代碼為:

  <div class="sendkeydown">
	  <span class="sendkey" key="1">1</span>
	  <span class="sendkey" key="2">2</span>
	  <span class="sendkey" key="3">3</span>
	  <span class="sendkey" key="4">4</span>
	  <span class="sendkey" key="5">5</span>
	  <span class="sendkey" key="6">6</span>
	  <span class="sendkey" key="7">7</span>
	  <br>
	  <span class="sendkey funkey" key="Enter">⏎</span>
	  <span class="sendkey funkey" key="Backspace">⌫</span>
  </div>
	<style>
.sendkeydown {text-align: center;}
.sendkey {background: #fa7; width: 36px; height: 36px; display: inline-block; font-size: 24px; line-height: 36px; cursor: pointer; margin-top: 12px;}
.funkey {background: #7fa;}
	</style>
  <script>
	  window.addEventListener("click", function (e) {
		  if (e.target.classList.contains("sendkey")) {
			var ele = document.getElementById('puzzlecanvas');
			var event = new KeyboardEvent('keydown', {
				key: e.target.getAttribute("key")
			});
			ele.dispatchEvent(event);
		  }
	  });
  </script>

2 thoughts on “向html元素發送鍵盤事件”

Leave a Comment