【问题标题】:Passing Mouse Events through SVG Background通过 SVG 背景传递鼠标事件
【发布时间】:2017-10-02 22:29:37
【问题描述】:

我有两个 SVG 元素,每个元素都覆盖整个屏幕。

html,
body {
  height: 100%;
}

svg {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
<body>
  <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
    <rect x=0 y=0 width=50 height=50 fill='#ff0000' onclick="console.log(1)"></rect>
  </svg>
  <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
    <rect x=40 y=40 width=50 height=50 fill='#00ff00' onclick="console.log(2)"></rect>
  </svg>
</body>

即使方块不重叠,点击事件也永远不会传递给红色方块,因为带有绿色方块的 SVG 会覆盖整个屏幕并捕获任何点击事件。有没有办法在这两个方块上都有点击事件,而不用在同一个 SVG 中?

How can I pass ONLY clicks through a SVG with pointer-events? 之类的解决方案非常适合将点击事件传递到红色方块,但前提是您可以丢弃绿色方块上的所有事件。

【问题讨论】:

    标签: javascript css svg


    【解决方案1】:

    只需将指针事件 none 添加到 svg 标签。在 svg 内的所有其他内容上添加指针事件自动。仅使 svg 内的元素可点击,而不是父 sv​​g 标签。

    在 chrome 中工作。

    html,
    body {
      height: 100%;
    }
    
    svg {
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      pointer-events:none;
    }
    svg *{
      pointer-events:auto;
    }
    <body>
      <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
        <rect x=0 y=0 width=50 height=50 fill='#ff0000' onclick="console.log(1)"></rect>
      </svg>
      <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
        <rect x=40 y=40 width=50 height=50 fill='#00ff00' onclick="console.log(2)"></rect>
      </svg>
    </body>

    【讨论】:

    • pointer-events: none 将禁用 :hover css。
    • 这个答案对我来说真是一针见血——我有一个 SVG 被用作 Open Layers 地图上的径向菜单,但我仍然需要将地图拖到 SVG 的透明部分后面,这是一种享受!
    【解决方案2】:

    用另一个 svg 元素包裹你的 svg 元素。请参阅here 为什么会这样:如果&lt;svg&gt; 元素不是最外层的,则它不能成为指针事件的目标。这里最外层是 HTML 上下文的一部分,所以它的作用类似于 &lt;div&gt;

    html,
    body {
      height: 100%;
    }
    
    svg {
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
    }
    <body>
      <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
        <svg width="100%" height="100%">
          <rect x=0 y=0 width=50 height=50 fill='#ff0000' onclick="console.log(1)"></rect>
        </svg>
        <svg width="100%" height="100%">
          <rect x=40 y=40 width=50 height=50 fill='#00ff00' onclick="console.log(2)"></rect>
        </svg>
      </svg>
    </body>

    【讨论】:

    • 有趣的装置
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 2010-11-03
    • 2011-12-20
    • 2011-12-18
    • 1970-01-01
    • 2019-02-02
    相关资源
    最近更新 更多