ant-design-vue/components/_util/Dom/class-util.js

62 lines
1.4 KiB
JavaScript
Raw Normal View History

2017-12-27 08:13:26 +00:00
/* @flow */
/**
* Add class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
2019-01-12 03:33:27 +00:00
export function addClass(el, cls) {
2017-12-27 08:13:26 +00:00
/* istanbul ignore if */
if (!cls || !(cls = cls.trim())) {
2019-01-12 03:33:27 +00:00
return;
2017-12-27 08:13:26 +00:00
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
2019-01-12 03:33:27 +00:00
cls.split(/\s+/).forEach(c => el.classList.add(c));
2017-12-27 08:13:26 +00:00
} else {
2019-01-12 03:33:27 +00:00
el.classList.add(cls);
2017-12-27 08:13:26 +00:00
}
} else {
2019-01-12 03:33:27 +00:00
const cur = ` ${el.getAttribute('class') || ''} `;
2017-12-27 08:13:26 +00:00
if (cur.indexOf(' ' + cls + ' ') < 0) {
2019-01-12 03:33:27 +00:00
el.setAttribute('class', (cur + cls).trim());
2017-12-27 08:13:26 +00:00
}
}
}
/**
* Remove class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
2019-01-12 03:33:27 +00:00
export function removeClass(el, cls) {
2017-12-27 08:13:26 +00:00
/* istanbul ignore if */
if (!cls || !(cls = cls.trim())) {
2019-01-12 03:33:27 +00:00
return;
2017-12-27 08:13:26 +00:00
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
2019-01-12 03:33:27 +00:00
cls.split(/\s+/).forEach(c => el.classList.remove(c));
2017-12-27 08:13:26 +00:00
} else {
2019-01-12 03:33:27 +00:00
el.classList.remove(cls);
2017-12-27 08:13:26 +00:00
}
if (!el.classList.length) {
2019-01-12 03:33:27 +00:00
el.removeAttribute('class');
2017-12-27 08:13:26 +00:00
}
} else {
2019-01-12 03:33:27 +00:00
let cur = ` ${el.getAttribute('class') || ''} `;
const tar = ' ' + cls + ' ';
2017-12-27 08:13:26 +00:00
while (cur.indexOf(tar) >= 0) {
2019-01-12 03:33:27 +00:00
cur = cur.replace(tar, ' ');
2017-12-27 08:13:26 +00:00
}
2019-01-12 03:33:27 +00:00
cur = cur.trim();
2017-12-27 08:13:26 +00:00
if (cur) {
2019-01-12 03:33:27 +00:00
el.setAttribute('class', cur);
2017-12-27 08:13:26 +00:00
} else {
2019-01-12 03:33:27 +00:00
el.removeAttribute('class');
2017-12-27 08:13:26 +00:00
}
}
}