詳解css3 pointer-events(阻止hover、active、onclick等觸發事件)

一、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>

 

發佈了63 篇原創文章 · 獲贊 43 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章