【问题标题】:SVG: layering of objects regarding eventsSVG:关于事件的对象分层
【发布时间】:2021-12-26 15:34:29
【问题描述】:

我对 SVG 的分层和事件有疑问。

例如:https://stackblitz.com/edit/angular-ivy-rkxuic?file=src/app/app.component.ts

app.component.ts

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  
<svg xmlns="http://www.w3.org/2000/svg" height="400px" width="400px">
  <rect x="30" y="30" width="100" height="100" fill="grey" (mouseenter)="txtg='in grey'" (mouseleave)="txtg=''" />
  <rect x="70" y="70" width="50" height="50" fill="yellow"  
      (click)="txty='yellow clicked'" (mouseleave)="txty=''" pointer-events="all"/>
</svg>
<p>
txtg: {{txtg}}<br/>
txty: {{txty}}
  
  `,
})
export class AppComponent {
  txtg: string = '';
  txty: string = '';
}

  • 即使我在黄色中,我也想在灰色中,因为黄色在灰色中。 所以从悬停的角度来看,灰色应该在前景中,但黄色可见。

  • 但我也希望能够点击黄色 - 所以那个黄色应该在前台。

有没有办法让我两者兼得?

【问题讨论】:

  • 尝试为黄色添加pointer-events: none。可以在css中添加,也可以作为属性添加
  • 这对第一个请求有效,但对第二个请求无效(点击黄色应该可以)。

标签: css angular svg


【解决方案1】:

这两个rects 是兄弟姐妹,所以你不能冒泡这个事件。

要么在黄色矩形上复制mouseenter 事件:

<svg xmlns="http://www.w3.org/2000/svg" height="400px" width="400px">
    <rect x="30" y="30" width="100" height="100" fill="grey" 
        (mouseenter)="txtg='in grey'" 
        (mouseleave)="txtg=''" 
    />
    <rect x="70" y="70" width="50" height="50" fill="yellow" 
        (mouseenter)="txtg='in grey'"
        (click)="txty='yellow clicked'" 
        (mouseleave)="txty=''"
    />
</svg>

或者您将两者都包含在 g 中并在其上设置 mouseentermouseleave 事件:

<svg xmlns="http://www.w3.org/2000/svg" height="400px" width="400px">

    <g (mouseenter)="txtg='in grey'" (mouseleave)="txtg=''">
        <rect x="30" y="30" width="100" height="100" fill="grey" />
        <rect x="70" y="70" width="50" height="50" fill="yellow"
            (click)="txty='yellow clicked'" 
            (mouseleave)="txty=''" 
            pointer-events="all"
        />
    </g>
</svg>

【讨论】:

    猜你喜欢
    • 2012-03-29
    • 2011-05-06
    • 2010-10-19
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 2015-11-14
    • 2012-10-03
    相关资源
    最近更新 更多