通过jQuery执行键盘命令

Executing keyboard command via jQuery

本文关键字:命令 键盘 执行 jQuery 通过      更新时间:2023-09-26

我想在页面加载时执行命令ctrl+0。以下是我目前所拥有的:

$( document ).ready(function() {
    var press = jQuery.Event("keypress");
    press.ctrlKey = true;
    press.which = 48;
    trigger(press);
});

这并没有触发ctrl+0,也破坏了页面上的另一个div。

我做错了什么?我该如何解决?

您应该使用$(document).trigger(press),它将在整个document上跟踪keydowns

$(document).keydown(function(e) {
  if (e.keyCode == 48 && e.ctrlKey)
    $("body").append("<p>ctrl+0 Detected!</p>");
});
$(document).ready(function() {
  var e = jQuery.Event("keydown");
  e.keyCode = 48; // # Some key code value
  e.ctrlKey = true;
  $(document).trigger(e);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

您不能在brownser中触发ctrl+0,这是一个安全问题。但是你可以得到brownser的缩放比例。

设备像素纵横比http://tombigel.github.io/detect-zoom/

项目的githubhttps://github.com/tombigel/detect-zoom

也许对你的项目有用。