js事件代理

js事件代理可以方便我们多个同组对象添加统一事件,简化代码,事件代理使用的是事件冒泡特性(事件会随着子父级层次向外传递),点击子元素触发事件后在父元素获取,通过事件的目标对象确定具体触发的子元素。

js原生事件绑定,兼容方法见我的博客另一篇文章:http://blog.csdn.net/qq_14886653/article/details/52495000

简单例子,解释下js事件代理

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
        <title></title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }

            ul {
                width: 500px;
                height: 50px;
                margin: 50px auto;
            }

            ul li {
                width: 50px;
                height: 50px;
                margin-right: 20px;
                float: left;
                list-style: none;
            }

            ul li:first-child {
                background: red;
            }

            ul li:nth-child(2) {
                background: green;
            }

            ul li:nth-child(3) {
                background: blue;
            }

            ul li:nth-child(4) {
                background: yellow;
            }

            ul li:nth-child(5) {
                background: pink;
            }
        </style>
    </head>

    <body>
        <ul id="ul">
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
        </ul>
        <script type="text/javascript">
            HTMLElement.prototype.__defineGetter__("currentStyle", function() {
                return this.ownerDocument.defaultView.getComputedStyle(this, null);
            });//兼容性写法,兼容谷歌和火狐,获得非内联样式中的样式值,源自百度,可以自己百度。
            var ul = document.getElementById("ul");
            var body = document.getElementsByTagName("body")[0];
            ul.addEventListener("click", click_btn, false);

            function click_btn(event) {
                event = event || window.event;
                //判断触发时间目标元素的标签名,忽视其他元素点击事件
                if (event.target.tagName == 'LI'){
                    body.style.background = event.target.currentStyle.background;
                }
                else{
                    return;
                }
            }       </script>
    </body>

</html>

上述代码功能,点击颜色方块,改变body背景色为li标签的背景色。通过事件对象进行判断,得到具体的触发事件的元素,进行相应的事件处理。

时间代理的优点:减少代码量,方便快捷。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值