leohxj
9/6/2013 - 6:14 AM

延迟加载class

延迟加载class

function delaySetClass(elementId, delayTime, classToAdd, classToRemove, callback) {
    var element = document.getElementById(elementId);

    if (element == null) {
        console.log(elementId + 'does not exit!');
        return;
    }

    var delayTimeout = setTimeout(function() {
        var oldClassName = element.className,
        newClassName='';

        if (typeof classToAdd == 'string') {
            newClassName = oldClassName + ' ' + classToAdd;
        } else if (Object.prototype.toString.call(classToAdd) === '[object Array]') {
            newClassName = oldClassName + ' ' + classToAdd.join(' ');
        }
        element.className = newClassName;
        oldClassName = newClassName;

        if (typeof classToRemove == 'string') {
            newClassName = oldClassName.replace(classToRemove, '').trim();
        } else if (Object.prototype.toString.call(classToRemove) === '[object Array]') {
            classToRemove.forEach(function(item) {
                            oldClassName = oldClassName.replace(item, '');
                        });
            newClassName = oldClassName.trim();
        }

        element.className = newClassName;
        
        if (typeof callback == 'function') {
            callback();
        }
    }, delayTime);

    return delayTimeout;
}