style.mjs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { isNumber, isStringNumber } from '../types.mjs';
  2. import { isClient } from '@vueuse/core';
  3. import { camelize, isObject, isString } from '@vue/shared';
  4. import { entriesOf, keysOf } from '../objects.mjs';
  5. import { debugWarn } from '../error.mjs';
  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(
  47. ([prop, value2]) => setStyle(element, prop, value2)
  48. );
  49. } else {
  50. const key = camelize(styleName);
  51. element.style[key] = value;
  52. }
  53. };
  54. const removeStyle = (element, style) => {
  55. if (!element || !style)
  56. return;
  57. if (isObject(style)) {
  58. keysOf(style).forEach((prop) => removeStyle(element, prop));
  59. } else {
  60. setStyle(element, style, "");
  61. }
  62. };
  63. function addUnit(value, defaultUnit = "px") {
  64. if (!value && value !== 0)
  65. return "";
  66. if (isNumber(value) || isStringNumber(value)) {
  67. return `${value}${defaultUnit}`;
  68. } else if (isString(value)) {
  69. return value;
  70. }
  71. debugWarn(SCOPE, "binding value must be a string or number");
  72. }
  73. export { addClass, addUnit, classNameToArray, getStyle, hasClass, removeClass, removeStyle, setStyle };
  74. //# sourceMappingURL=style.mjs.map