css的pointer-events属性实现下面元素可点击


是否曾经有过这样的经历:把一个元素置于另一个元素之上,而希望下面的那个元素成为可点击的?现在,利用css的pointer-events属性即可做到。

CSS pointer-events

Pointer-events原本来源于SVG,目前在很多浏览器中已经得到体现。不过,要让任何HTML元素生效还得借助于一点点css。该属性称之为pointer-events,基本上可以将它设置为auto,这是正常的行为,而“none”是一个有趣的属性。

将它应用到一个元素

如果你已经设置一个元素的css属性为pointer-events: none。它将不会捕获任何click事件,而是让事件穿过该元素到达下面的元素,就像这样:

<style
    .overlay { 
        pointer-events: none; 
    }
</style>
<div id="overlay" class="overlay"></div>

浏览器支持

到目前为止,Firefox 3.6+、Safari 4 和Google Chrome支持Pointer-events。我觉得Opera和IE肯定会尽快赶上,我不知道它们的计划中是否支持它。

小演示

我将Pointer-events行为的演示放在一起,在那里你可以自己测试它。正如你看到的那样,右边灰色的盒子阻止单击下面的链接。但是,如果你单击checkbox对其禁用Pointer-events。下面链接的click事件将被触发。

演示页完整的代码如下所示:

<!DOCTYPE html>
<html lang="en">
<head
    <meta charset="utf-8"
    <title>CSS pointer events</title
    <style
        .container { 
            position: relative; 
            width: 370px; 
            font: 15px Verdana, sans-serif; 
            margin: 10px auto; 
        
  
        .overlay { 
            position: absolute; 
            right: 0px; 
            top: 0; 
            width: 40px; 
            height: 40px; 
           background: rgba(0, 0, 0, 0.5); 
        
        .pointer-events-none { 
            pointer-events: none; 
        
    </style
    <script
        window.onload = function () { 
            document.getElementById("enable-disable-pointer-events").onclick = function () { 
                document.getElementById("overlay").className = "overlay " + ((this.checked)? "pointer-events-none" : ""); 
            }; 
        }; 
    </script>
</head>
<body>
<div class="container"
    <a href="http://twitter.com">Twitter</a>, <a href="http://twitter.com">Twitter</a>, <a href="http://twitter.com">Twitter</a>, <a href="http://twitter.com">Twitter</a>, <a href="http://twitter.com">Twitter</a>, <a href="http://twitter.com">Twitter</a>, <a href="http://twitter.com">Twitter</a>, <a href="http://twitter.com">Twitter</a>, <a href="http://twitter.com">Twitter</a>, <a href="http://twitter.com">Twitter</a>, <a href="http://twitter.com">Twitter</a>, <a href="http://twitter.com">Twitter</a>, <a href="http://twitter.com">Twitter</a>, <a href="http://twitter.com">Twitter</a>, 
    <div id="overlay" class="overlay"></div
    <p
        <input id="enable-disable-pointer-events" type="checkbox"
        <label for="enable-disable-pointer-events">Disable pointer events for grey box</label
    </p>
</div>
</body>
</html>

实际的例子

如果你进入Twitter(国内好像不能登录到该网站,如下图所示)的开始页,而且没有登录。在底部你将看到很多列出的标签。在右边的一个元素,有一张褪色的图片覆盖其上产生这样的效果。不幸的是下面的链接无法点击。如果你在css中添加一行代码,就可以了。

现在,如果你需要这种效果,你有了一个非常简单的方法。

http://robertnyman.com/2010/03/22/css-pointer-events-to-allow-clicks-on-underlying-elements/#respond


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3