style.js 2.4 KB

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