JavaScript侦听Html元素Attribute的变化

来源:互联网 发布:无锡数据恢复 编辑:程序博客网 时间:2024/05/16 12:01
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();
            }
        });
    });

0 0
原创粉丝点击