Skip to content

Instantly share code, notes, and snippets.

@leohxj
Created September 6, 2013 06:14
Show Gist options
  • Select an option

  • Save leohxj/6460148 to your computer and use it in GitHub Desktop.

Select an option

Save leohxj/6460148 to your computer and use it in GitHub Desktop.
延迟加载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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment