添加类名
HTMLElement.prototype.addClassName = function (className) {
if (!className) return
const el = this
const classNames = el.className.split(' ').filter(i => !!i)
if (!classNames.includes(className)) {
classNames.push(className)
}
el.className = classNames.join(' ')
}
删除类名
HTMLElement.prototype.removeClassName = function (className) {
if (!className) return
const el = this
const classNames = el.className.split(' ').filter(i => !!i)
const index = classNames.indexOf(className)
if (index !== -1) {
classNames.splice(index, 1)
}
el.className = classNames.join(' ')
}
引用
const oDiv = document.getElementById('test')
// 添加类名
oDiv.addClassName('show')
// 移除类名
oDiv.removeClassName('test')