【问题标题】:Trigger method with click and drag (Angular)单击并拖动触发方法(角度)
【发布时间】:2019-04-17 00:00:14
【问题描述】:

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

我想在 Angular 中创建它。

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

它应该是这样的:

下面是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;
}

【问题讨论】:

  • 您需要使用事件mousedownmousemovemouseup 进行设置。我建议在mousedown 发生时在组件mouseIsDown 中设置一个标志,然后在标志为真时更改mousemove 中的突出显示,然后在mouseup 中取消设置标志。
  • 谢谢。你见过这样的例子吗?

标签: angular click drag


【解决方案1】:

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

检查这个堆栈闪电战 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
}

【讨论】:

    【解决方案2】:

    正如 cmets 中所建议的,您正在寻找各种 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

    【讨论】:

      猜你喜欢
      • 2019-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-30
      • 2020-06-30
      • 2012-09-22
      • 1970-01-01
      相关资源
      最近更新 更多