【问题标题】:Apply style to element when click outside of directive attribute element in Angular在Angular中的指令属性元素之外单击时将样式应用于元素
【发布时间】:2020-02-21 00:36:22
【问题描述】:

我有 svg 项目,当用户点击它们或悬停它们时,它们会突出显示它们的相应路径。

我正在使用指令来检测 onEnter onLeaveClick 事件。

当我悬停(我突出显示)然后当我离开元素时(我向下播放)它工作正常

然后,当我单击时,路径也会突出显示(

实际上发生的情况是当我点击其他地方时,突出显示停留。

我不能这样做的是,当我点击屏幕的其余部分时,我希望突出显示消失。

这是我的指令逻辑

export class HighlightDirective {
  constructor(private renderer:Renderer2 , private el: ElementRef) {}
  clicked=false
  @HostListener('mouseenter') onMouseEnter() {
    this.changeOpacity(1);
  }

  @HostListener('mouseleave') onMouseLeave() {
    if (!this.clicked) {
      this.changeOpacity(0);
    }
  }
  @HostListener('click') click() {
    this.changeOpacity(1);
    this.clicked = true;
  }
  changeOpacity(opacity: number) {
    this.renderer.setStyle(this.el.nativeElement.nextSibling, 'opacity', opacity);
  }

}

这是带有 Highlight 属性标签的 SVG 的一部分

 <g id="b1" transform="translate(-885 -562)">
    <g id="b1select">
      <ellipse id="Ellipse_1" data-name="Ellipse 1" cx="5.3" cy="5.3" rx="5.3" ry="5.3" transform="translate(1309.17 932.12)" fill="none" stroke="#b18802" stroke-width="1"/>
      <text id="B1-2" data-name="B1" transform="translate(1310.67 939.62)" fill="#b18802" font-size="6" font-family="ArialMT, Arial"><tspan x="0" y="0">B1</tspan></text>
    </g>
    <rect appHighlight (click)="openDialog($event)" id="container" width="12" height="11" transform="translate(1308.67 931.62)" fill="rgba(255,255,255,0)"/>
    <path id="b1-3" data-name="b1" d="M1093.763,1595.658v-82.417s5-14.987-18.452-16.644-40.9,2.386-54.093-11.537-132.873-159.193-132.873-159.193-6.456-10.249-24.986-14.661-9.858-17.907-4.728-25.235,39.039-47.23,39.039-47.23" transform="translate(208.67 -656.38)" fill="none" stroke="#efcf2f" stroke-linecap="round" stroke-width="2"/>
  </g>

这是stackBlitz上的一个例子

【问题讨论】:

    标签: javascript html css angular svg


    【解决方案1】:
    document.removeEventListener('mousedown', this.scroll);
    

    我使用的是每当 mousedown 事件触发 removeListner 删除滚动事件。我们在使用 addEventListner() 之前添加的。 this.scroll 是你定义的事件来做你想做的事。

    【讨论】:

    • 对不起,我不明白你想要做什么
    • 查看这个 stackblitz 链接。我在这里所做的是先点击“点击我”按钮。然后菜单上下文打开。然后,当您单击文档中任意位置的菜单外部时,菜单将关闭并加载您的样式类相关条件。在这里,我使用了 [ngClass] 并有条件地加载了 .css 类。 stackblitz.com/edit/angular-fxjxzv.
    • 谢谢,这是一个可行的解决方案,所以我会接受它,自定义指令内的点击处理方法是什么
    猜你喜欢
    • 1970-01-01
    • 2016-04-30
    • 2013-10-17
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 2014-12-17
    • 1970-01-01
    相关资源
    最近更新 更多