简体   繁体   English

使用html按钮按箭头键或直接按

[英]Press an Arrow key using a html button or simply press it

I want to press an arrow key using an html button. 我想使用html按钮按箭头键。 I have so far found only trigger or simulate events. 到目前为止,我发现仅触发或模拟事件。

Like in jquery we have a .click() to have a mouse click, similarly I am trying to have a arrowUp() similarly for all arrow keys. 像在jquery中一样,我们有一个.click()来单击鼠标,类似地,我试图为所有箭头键都类似地拥有arrowUp()。 I am ultimately trying to implement this in an angular app. 我最终试图在一个有角度的应用程序中实现这一点。

Please help. 请帮忙。

UPDATE 更新

Need to fire an up arrow key or F1 key event like the .click(), using typescript/javascript. 需要使用typescript / javascript触发向上箭头键或F1键事件,例如.click()。

If an F1 key event is fired it should open up some kind of windows help tab. 如果触发了F1键事件,则应打开某种Windows帮助标签。 So in a page if an up or down arrow key is fired, the page should scroll up or down accordingly. 因此,在页面中,如果触发了向上或向下箭头键,则页面应相应地向上或向下滚动。

In Angular you need to bind the html button to a variable using ViewChild 在Angular中,您需要使用ViewChild将html按钮绑定到变量

<button #myButton>

And in the controller 并在控制器中

@ViewChild('myButton')
myButton: ElementRef;

Then you can call the event 那你可以打电话给活动

const event = new KeyboardEvent('keydown',{ 'which': '40'}); //down
this.myButton.nativeElement.dispatchEvent(event);

You can use the different keycodes for the arrows: 您可以为箭头使用不同的键控代码:

37-left 38-up 39-right 40-down 37左38向上39右40向下

Working fiddle: https://jsfiddle.net/pwmcfgkn/4/ 工作提琴: https : //jsfiddle.net/pwmcfgkn/4/

Angular has a built in key listener event handler like here , but it seems limited to just several keys like Enter, Shift Control as described in the Github Page Angular具有像这里这样的内置键侦听器事件处理程序,但似乎仅限于几个键,如Github页面中所述的Enter和Shift Control

However, you can use HTML's robust key event handler like 但是,您可以使用HTML的强大键事件处理程序,例如

window.addEventListener("keydown", function (event) {
  if (event.defaultPrevented) {
    return; // Do nothing if the event was already processed
  }

  switch (event.key) {
    case "Down": // IE/Edge specific value
    case "ArrowDown":
      // Do something for "down arrow" key press.
      break;
    case "Up": // IE/Edge specific value
    case "ArrowUp":
      // Do something for "up arrow" key press.
      break;

    default:
      return; // Quit when this doesn't handle the key event.
  }

  // Cancel the default action to avoid it being handled twice
  event.preventDefault();
}, true);

This example can be found here , and the full list of keys, including arrow keys here 可以在此处找到该示例,以及完整的按键列表,包括此处的箭头键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM