欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Chrome中捕获和冒泡的demo

程序员文章站 2022-07-14 09:30:07
...
一言以蔽之,曰:“先捕获,后冒泡!”


该代码只适合于有addEventListener方法的浏览器,没有做判断和容错,使用方法为:拷贝代码并保存为xxx.html,用浏览器运行,点击中间的click me,于是有了一个动画效果,很粗糙,只为了庆祝程序员节。

<!DOCTYPE html>
<html>
<head>
  <title>Capture & Bubble</title>
  <style type="text/css">
  div { float: left;border: 1px solid #CCC;padding: 30px;background-color: #FFF; text-align: center; vertical-align: middle;}
  </style>
</head>
<body>
<div>
  <div>
    <div>
      <div>
        <div style="width:100px; height:100px; line-height: 100px; cursor:pointer;">Click Me</div>
      </div>
    </div>
  </div>
</div>
<script type="text/javascript">
var divList = document.getElementsByTagName('div');
var timer = 0;
for (var i = 0, len = divList.length; i < len; i ++) {
    (function(j) {
        var divNode = divList[j];
        var changeBg = function(type) {
            if (!divNode.getAttribute('hasClicked')) {
                divNode.setAttribute('hasClicked', 0);
            }
            var hasClicked = divNode.getAttribute('hasClicked') - 0;
            if (hasClicked <= 2) {
                hasClicked ++;
                divNode.setAttribute('hasClicked', hasClicked);
                timer ++;
                if (hasClicked == 1) {
                    window.setTimeout(function() {
                        divNode.style.backgroundColor = '#444';
                        console.log(type);
                    }, timer * 1000);
                } else {
                    window.setTimeout(function() {
                        divNode.style.backgroundColor = '#FFF';
                        divNode.setAttribute('hasClicked', 0);
                        console.log(type);
                    }, timer * 1000);
                }
            }
        };
        divNode.addEventListener('click', function(e) {
            // capture
            changeBg('capture');
        }, true);
        divNode.addEventListener('click', function(e) {
            // bubble
            changeBg('bubble');
        }, false);
    })(i);
}
</script>
</body>
</html>