繁体   English   中英

在 Angular 中的指令属性元素外部单击时将样式应用于元素

[英]Apply style to element when click outside of directive attribute element in Angular

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

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

当我 hover (我突出显示)然后当我离开元素时它工作正常(我淡化)

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

实际上,当我在其他地方单击突出显示时,会发生什么。

我不能这样做的是,当我单击屏幕的 rest 时,我希望突出显示消失。

这是我的指令逻辑

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);
  }

}

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

 <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的一个例子

document.removeEventListener('mousedown', this.scroll);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM