// HTMLElement 要操作的元素,cls类名
export const hasClass = function (obj: HTMLElement, cls: string) {
return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
};
export const addClass = function (obj: HTMLElement, cls: string) {
if (!hasClass(obj, cls)) obj.className += ' ' + cls;
};
export const removeClass = function (obj: HTMLElement, cls: string) {
if (hasClass(obj, cls)) {
const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
obj.className = obj.className.replace(reg, ' ');
}
};
export const toggleClass = function (obj: HTMLElement, cls: string) {
if (hasClass(obj, cls)) {
removeClass(obj, cls);
} else {
addClass(obj, cls);
}
};
06-28
2250
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)