Browse Source

fix: set custom properties in style correctly (#1854)

Tom Pohl 3 years ago
parent
commit
1b20bf7ef3

+ 1 - 1
packages/alpinejs/src/utils/styles.js

@@ -13,7 +13,7 @@ function setStylesFromObject(el, value) {
     Object.entries(value).forEach(([key, value]) => {
         previousStyles[key] = el.style[key]
 
-        el.style[key] = value
+        el.style.setProperty(key, value)
     })
 
     setTimeout(() => {

+ 22 - 0
tests/cypress/integration/directives/x-bind-style.spec.js

@@ -21,3 +21,25 @@ test('style attribute object bindings are merged with existing styles',
         get('span').should(haveAttribute('style', 'display: block; color: red;'))
     }
 )
+
+test('CSS custom properties are set',
+    html`
+        <div x-data="{custom_color: '#f00'}">
+            <span style="color: var(--custom-prop)" x-bind:style="{ '--custom-prop': custom_color }">I should be red</span>
+        </div>
+    `,
+    ({ get }) => {
+        get('span').should(haveAttribute('style', 'color: var(--custom-prop); --custom-prop:#f00;'))
+    }
+)
+
+test('existing CSS custom properties are preserved',
+    html`
+        <div x-data="{link: 'var(--custom-prop-a)'}">
+            <span style="color: var(--custom-prop-b); --custom-prop-a: red" x-bind:style="{ '--custom-prop-b': link }">I should be red</span>
+        </div>
+    `,
+    ({ get }) => {
+        get('span').should(haveAttribute('style', 'color: var(--custom-prop-b); --custom-prop-a: red; --custom-prop-b:var(--custom-prop-a);'))
+    }
+)