单击并拖动的触发方法(Angular)

问题描述 投票:1回答:2

我有一个表,我希望用户能够通过单击并拖动多个单元格来触发方法(即,更改单击/拖动的单元格的背景颜色)。

我想在Angular中创建它。

当我使用click方法时,它仅在首次单击的单元格上触发,而不是在鼠标向下的任何其他单元格上触发(即,我必须单击每个单元格以突出显示或取消突出显示)。

它应该是这样的:enter image description here

下面是stackblitz

零件:

<table>
  <TR>
    <TD *ngFor="let b of colCount" 
        (click)="b.highlight = !b.highlight" 
        [class.highlight]="b.highlight"
    ></TD>
  </TR>
</table>

TS:

 colCount = [{highlight: true},{highlight: true},{highlight: true},{highlight: true},{highlight: true},{highlight: true}]

  select(b) {
    console.log(b)
    b.highlight = !b.highlight
  }

CSS:

td {
 border: 1px solid black;
 width: 20px !important;
 height: 20px !important;
}

.highlight {
  background-color: blue;
}
angular click drag
2个回答
1
投票

它只是检查鼠标是否已关闭并进入下一个块。

检查这个stackblitz https://stackblitz.com/edit/angular-55xflc

HTML

<table>
  <tr>
    <td *ngFor="let b of colCount" 
        (mousedown)="mousedown(b)" 
        (mouseover)="mouseover(b)"
        (window:mouseup)="mouseup()"
        [class.highlight]="b.highlight"
    ></td>
  </tr>
</table>

TS

down: boolean = false

colCount = [{highlight: true},{highlight: true},{highlight: true},{highlight: true},{highlight: true},{highlight: true}]

mousedown(b) {
  this.down = true
  if (this.down) {
    b.highlight = !b.highlight
  }
}

mouseover(b) {
  if (this.down) {
    b.highlight = !b.highlight
  }
}

mouseup() {
  this.down = false
}

0
投票

正如评论中所建议的那样,你正在寻找各种mouse事件,这样的事情应该可以解决。

您可能需要稍微调整一下以确保它完全符合您的要求,但这应该是一个很好的起点。

<table>
  <TR>
    <TD *ngFor="let b of colCount"
        (click)="b.highlight = !b.highlight"
        (mousedown)="mouseIsDown = true"
        (mouseup)="mouseIsDown = false"
        (mouseleave)="mouseIsDown ? b.highlight = !b.highlight : null"
        [class.highlight]="b.highlight"
    ></TD>
  </TR>
</table>

export class Component {
  mouseIsDown = false;
  ...
}

Demo

© www.soinside.com 2019 - 2024. All rights reserved.