一、pointer-events 介绍

 1、pointer-events 更像是JavaScript,它能够:

  • 阻止用户的点击动作产生任何效果
  • 阻止缺省鼠标指针的显示
  • 阻止CSS里的 hover 和 active 状态的变化触发事件
  • 阻止JavaScript点击动作触发的事件
  • 通过其他方式绑定的事件还是会触发的,比如键盘事件等。

 2、pointer-events 是CSS3的一个属性,支持的值非常多,其中大部分都是和SVG有关。对于前端日常开发而言,只要了解none、auto就可以用于大部分的需求场景

/* Keyword values */
pointer-events: auto;
pointer-events: none;
pointer-events: visiblePainted; /* SVG only */
pointer-events: visibleFill;    /* SVG only */
pointer-events: visibleStroke;  /* SVG only */
pointer-events: visible;        /* SVG only */
pointer-events: painted;        /* SVG only */
pointer-events: fill;           /* SVG only */
pointer-events: stroke;         /* SVG only */
pointer-events: all;            /* SVG only */

/* Global values */
pointer-events: inherit;
pointer-events: initial;
pointer-events: unset;
初始值 auto
适用元素 all elements
是否是继承属性 yes
适用媒体 visual
计算值 as specified
Animation type discrete
正规顺序 the unique non-ambiguous order defined by the formal grammar

  二、pointer-events属性值详解

  • auto——效果和没有定义pointer-events属性相同,鼠标不会穿透当前层。在SVG中,该值和visiblePainted的效果相同。

  • none——元素永远不会成为鼠标事件的target。但是,当其后代元素的pointer-events属性指定其他值时,鼠标事件可以指向后代元素,在这种情况下,鼠标事件将在捕获或冒泡阶段触发父元素的事件侦听器。

  • 其它属性值为SVG专用,这里不再多介绍了。(可以参看文档https://developer.mozilla.org/zh-CN/docs/Web/CSS/pointer-events

三、浏览器兼容

Firefox 3.6+和chrome 2.0+ 以及safari 4.0+都支持这个CSS3属性,IE6/7/8/9都不支持(IE11又支持,不过很好的一点是在ie中给a加disabled 点击事件自动无效。),Opera在SVG中支持。 但是 该属性HTML中 不支持 

四、开发中的按例

1、提交页面,提交按钮点击后,添加这个样式属性(style="pointer-events"),来防止重复提交。

2、让链接不能点击。
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
<meta charset="utf-8" />
<title></title>

<style>
a[href="http://example.com"] {
  pointer-events: none;
}
</style>
</head>
<body>
<ul>
	<li><a href="https://html.cn/">HTML中文网</a></li>
	<li><a href="http://example.com">一个不能点击的链接</a></li>
</ul>
</body>
</html>

 3、让鼠标点击穿透上方的 div

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <style>
      .top {
          width: 100px;
          height: 90px;
          position: absolute;
          top: 0;
          left: 65px;
          background: yellow;
          opacity: 0.5;
          pointer-events: none;
      }
    </style>
  </head>
  <body>
    <!-- 下方的链接 -->
    <ul>
      <li><a href="http://www.hangge.com">航歌</a></li>
        <li><a href="http://www.hangge.com">hangge.com</a></li>
    </ul>
    <!-- 上方黄色div -->
    <div class="top"></div>
  </body>
</html>

 

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐