style.mjs 2.2 KB

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