【问题标题】:how can I move a div by 10px with press of arrow keys in angular 12?如何通过按角度 12 的箭头键将 div 移动 10px?
【发布时间】:2021-09-14 03:56:03
【问题描述】:

我只想通过按箭头按钮来控制(将一个位置移动到另一个位置)div。 div 也应该通过单击按钮 div 移动。我正在尝试移动被其他四个 div 包围的中心 div。当我点击左 div 时,中心 div 应该向左移动,如果我点击右 div,那么中心 div 应该向右移动,依此类推。我知道如何在 javaScript 中做,对 angular 不熟悉。

goLeft(ev:any){

    //what should I write here, on mouse click move the div by 10px?
  }


if(event.key == "ArrowDown"){
      // what shouls I wright here to move div by 10px from keyboard event.
      console.log(event.key);
    }

【问题讨论】:

  • 您可以使用在 JavaScript 中使用的相同代码来执行此操作,它也可以在 Angular 中工作。
  • 请分享代码,解释您已经尝试过的内容以及它与您的预期有何不同。

标签: angular angular12


【解决方案1】:

为自己创建一个方法,例如:

move(element: HTMLElement, moveBy: number) {
    // move element
    element.style.top = element.getBoundingClientRect().top + moveBy + "px";
    element.style.left = element.getBoundingClientRect().left + moveBy + "px";
}

现在在您的点击处理程序中调用此方法,例如在您的模板中可以访问 html 元素。抱歉,我目前在手机上,所以可能会有错误。您必须添加一个侦听器,例如:

  @HostListener('window:mouseup', ['$event'])
      public mouseup(_: MouseEvent): any {
         // implement your action here
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2013-10-14
    相关资源
    最近更新 更多