Home  >  Article  >  Web Front-end  >  支持事件穿透?使用pointer-events样式_html/css_WEB-ITnose

支持事件穿透?使用pointer-events样式_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:51:271521browse

  使用绝对定位元素,让元素A完全盖住元素B时,如何通过元素A来响应元素B的事件呢?

  上图可以用下面的SVG代码来实现:

<svg width="200" height="180">    <rect x="50" y="50" width="50" height="50" fill="#f34b5b" onclick="alert('Clicked')"></rect>    <rect x="20" y="20" width="160" height="140" fill="#FEDDCE" opacity="0.8"></rect></svg>

  第一个rect被第二个rect完全盖住,因此无法响应onclick事件。在传统解决办法中,我们需要编写JavaScript代码来实现事件穿透,即首先响应第二个rect元素的onclick事件,通过坐标值来判断点击位置是否位于第一个rect元素的范围内,从而决定是否触发第一个rect元素的onclick事件。但是如果图形和图形之间的关系比较复杂的话,自己编写代码工作量会很大,而且代码执行效率也不高。好在我们可以通过一个CSS样式来解决该问题:

pointer-events: none;

  将该样式加到第二个rect元素上,可以很轻松地实现事件穿透效果。该样式可以应用到任何DOM节点上,所有绝对定位的元素都适用,所有现代主流浏览器都已经支持该样式(经测试IE11也已经支持)。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn