【问题标题】:disable all button and links in a div禁用 div 中的所有按钮和链接
【发布时间】:2018-10-27 08:15:53
【问题描述】:

我正在尝试禁用 div 内的所有点击事件。我禁用了整个 div,但这对我来说不是解决方案,因为我有 mouseEnter 事件需要继续工作。

问题是它是我在应用程序的不同部分使用的指令,所以这个 div 有不同的结构,有时按钮是“直接子”,有时它在第二级。

这是我的尝试,它有效,但我发现它“脏”:

<div #mydirective>
  <button (click)="function1()">button</button>
  <div>
    <a (click)="function2()">link</a>
  </div>
</div>

//directive ts
var children = this.element.nativeElement.children;
for (let child of children) {
  this.renderer.setAttribute(child, 'disabled', 'true'); //for button
  this.renderer.addClass(child, 'disabled'); //for links
  var grandchildren = child.children;
  for (let grandchild of grandchildren) {         
    this.renderer.setAttribute(grandchild, 'disabled', 'true');
    this.renderer.addClass(grandchild, 'disabled');
  }
}

我相信它应该更容易,有什么方法可以在我的 div 中找到所有按钮和链接?

【问题讨论】:

  • 为什么不使用表单。这样你就可以设置验证逻辑来​​决定表单内的按钮是否被禁用?我假设你也有一些意见。
  • 它需要对我的代码进行大量更改,使用指令的想法是尽可能减少更改。但是,如果我找不到其他选项,我可以选择此选项。谢谢!

标签: angular angular5 angular2-directives angular-directive


【解决方案1】:

如果你想禁用所有鼠标点击..然后有条件地添加一个css类到那个div来禁用所有指针事件。

在 html 文件中。

<div class="your-class">
  // buttons and content goes here.
</div>

在 css/scss 文件中。

.your-class {
  pointer-events: none;
}

【讨论】:

  • 谢谢,但正如我在帖子中所说,这不是一个选项,因为我需要 mouseEnter 仍然工作
  • 通过使用指针事件来防止元素成为鼠标事件的目标并不一定意味着该元素上的鼠标事件侦听器不能或不会被触发。如果元素的其中一个子元素明确设置了指针事件以允许该子元素成为鼠标事件的目标,则任何针对该子元素的事件都将在事件沿父链传播时通过父元素,并在视情况而定。
猜你喜欢
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
  • 2021-05-09
  • 2016-01-15
  • 1970-01-01
  • 2020-05-16
相关资源
最近更新 更多