style.mjs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { isNumber, isStringNumber } from '../types.mjs';
  2. import { isClient } from '@vueuse/core';
  3. import { entriesOf, keysOf } from '../objects.mjs';
  4. import { debugWarn } from '../error.mjs';
  5. import { camelize, isObject, isString } from '@vue/shared';
  6. const SCOPE = "utils/dom/style";
  7. const classNameToArray = (cls = "") => cls.split(" ").filter((item) => !!item.trim());
  8. const hasClass = (el, cls) => {
  9. if (!el || !cls)
  10. return false;
  11. if (cls.includes(" "))
  12. throw new Error("className should not contain space.");
  13. return el.classList.contains(cls);
  14. };
  15. const addClass = (el, cls) => {
  16. if (!el || !cls.trim())
  17. return;
  18. el.classList.add(...classNameToArray(cls));
  19. };
  20. const removeClass = (el, cls) => {
  21. if (!el || !cls.trim())
  22. return;
  23. el.classList.remove(...classNameToArray(cls));
  24. };
  25. const getStyle = (element, styleName) => {
  26. var _a;
  27. if (!isClient || !element || !styleName)
  28. return "";
  29. let key = camelize(styleName);
  30. if (key === "float")
  31. key = "cssFloat";
  32. try {
  33. const style = element.style[key];
  34. if (style)
  35. return style;
  36. const computed = (_a = document.defaultView) == null ? void 0 : _a.getComputedStyle(element, "");
  37. return computed ? computed[key] : "";
  38. } catch (e) {
  39. return element.style[key];
  40. }
  41. };
  42. const setStyle = (element, styleName, value) => {
  43. if (!element || !styleName)
  44. return;
  45. if (isObject(styleName)) {
  46. entriesOf(styleName).forEach(([prop, value2]) => setStyle(element, prop, value2));
  47. } else {
  48. const key = camelize(styleName);
  49. element.style[key] = value;
  50. }
  51. };
  52. const removeStyle = (element, style) => {
  53. if (!element || !style)
  54. return;
  55. if (isObject(style)) {
  56. keysOf(style).forEach((prop) => removeStyle(element, prop));
  57. } else {
  58. setStyle(element, style, "");
  59. }
  60. };
  61. function addUnit(value, defaultUnit = "px") {
  62. if (!value)
  63. return "";
  64. if (isNumber(value) || isStringNumber(value)) {
  65. return `${value}${defaultUnit}`;
  66. } else if (isString(value)) {
  67. return value;
  68. }
  69. debugWarn(SCOPE, "binding value must be a string or number");
  70. }
  71. export { addClass, addUnit, classNameToArray, getStyle, hasClass, removeClass, removeStyle, setStyle };
  72. //# sourceMappingURL=style.mjs.map