JavaScript侦听Html元素Attribute的变化

1、定义JQuery插件:
 (function ($) {
        var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
        function isDOMAttrModifiedSupported() {
            var p = document.createElement('p');
            var flag = false;
            if (p.addEventListener) p.addEventListener('DOMAttrModified', function () {
                flag = true
            }, false);
            else if (p.attachEvent) p.attachEvent('onDOMAttrModified', function () {
                flag = true
            });
            else return false;
            p.setAttribute('id', 'target');
            return flag;
        }
        $.fn.attrChange = function (callback) {
            if (MutationObserver) {
                var options = {
                    subtree: false,
                    attributes: true
                };
                var observer = new MutationObserver(function (mutations) {
                    mutations.forEach(function (e) {
                        callback.call(e.target, e.attributeName);
                    });
                });
                return this.each(function () {
                    observer.observe(this, options);
                });
            } else if (isDOMAttrModifiedSupported()) {
                return this.on('DOMAttrModified', function (e) {
                    callback.call(this, e.attrName);
                });
            } else if ('onpropertychange' in document.body) {
                return this.on('propertychange', function (e) {
                    callback.call(this, window.event.propertyName);
                });
            }
        }
    })(jQuery); 

2、使用:监听方法将传入一个属性名称,根据名称判断哪个属性值进行了改变。
$(function () {
        $('.t-refresh').attrChange(function (attrName) {
            var contentArea = $(this).parent().parent().prev();
            if (attrName == 'class' && $(this).attr('class') == 't-icon t-refresh t-loading') {
                if (contentArea.offset().left == 0 && contentArea.offset().top == 0)
                    return false;
                $('#grid_splash').show().css({
                    height: contentArea.height(),
                    width: contentArea.width(),
                    left: contentArea.offset().left,
                    top: contentArea.offset().top,
                    opacity: 0.9
                });
            } else if (attrName == 'class' && $(this).attr('class') == 't-icon t-refresh') {
                $('#grid_splash').hide();
            }
        });
    });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值