仅出于遗留原因:
function toggleClassName(elementClassName, className) {
const originalClassNames = elementClassName.split(/\s+/);
const newClassNames = [];
let found = false;
for (let index = 0; index < originalClassNames.length; index++) {
if (originalClassNames[index] === '') {
continue;
}
if (originalClassNames[index] === className) {
found = true;
continue;
}
newClassNames.push(originalClassNames[index]);
}
if (!found) {
newClassNames.push(className);
}
return newClassNames.join(' ');
}
console.assert(toggleClassName('', 'foo') === 'foo');
console.assert(toggleClassName('foo', 'bar') === 'foo bar');
console.assert(toggleClassName('foo bar', 'bar') === 'foo');
console.assert(toggleClassName('bar foo', 'bar') === 'foo');
console.assert(toggleClassName('foo bar baz', 'bar') === 'foo baz');
console.assert(toggleClassName('foo-bar', 'foo') === 'foo-bar foo');
console.assert(toggleClassName('bar foo-bar', 'bar') === 'foo-bar');
console.assert(toggleClassName('bar bar bar foo-bar bar', 'bar') === 'foo-bar');
console.assert(toggleClassName(" \n\nbar-bar \nbar-baz foo", 'bar-baz') === 'bar-bar foo');
element.className = toggleClassName(element.className, 'foo');