使用JavaScript在组件中动态添加类不会更新样式。

huangapple go评论55阅读模式
英文:

Dynamically adding class using JavaScript in component does not update styles

问题

When I add a class defined in the <style> section of a Svelte component to an element at runtime via JavaScript, the CSS properties do not get applied although the class is indeed added. However, if the class is defined in another CSS file which is imported into the component, the code works. Why is this?

英文:

When I add a class defined in the &lt;style&gt; section of a Svelte component to an element at runtime via JavaScript, the CSS properties do not get applied although the class is indeed added. However, if the class is defined in another CSS file which is imported into the component, the code works. Why is this?

See the example below that reproduces this behavior:

&lt;script&gt;
  import { onMount } from &quot;svelte&quot;;

  function addClass() {
    document.getElementById(&#39;example&#39;).classList.add(&#39;foo&#39;);
    // class is added, but nothing appears to happen
  }
&lt;/script&gt;

&lt;div id=&quot;example&quot;&gt;Hi&lt;/div&gt;
&lt;button on:click={addClass}&gt;Add foo class&lt;/button&gt;

&lt;style&gt;
.foo {
  color : #be0000;
}
&lt;/style&gt;

答案1

得分: 1

&lt;style&gt;元素中声明的CSS在Svelte组件中默认是局部作用域的。为了实现这一点,Svelte会向选择器添加一个额外的类,例如svelte-buqcoz,并将该类添加到组件中匹配选择器的所有元素上。因此,仅在运行时添加bar类是不足以改变样式的。此外,在这种情况下,Svelte会看到bar类甚至没有被使用,因此不会为其生成任何CSS。

您可以使用:global来使该类在任何地方都可用,这将允许您动态应用该类。

:global(.bar) {
	color: #be0000;
}

另请参阅:https://svelte.dev/docs#component-format-style

英文:

CSS declared in the &lt;style&gt; element of a Svelte component are scoped to the component by default. To achieve this, Svelte adds an extra class to the selector, e.g. svelte-buqcoz, and also adds that class to all elements that match the selector in the component. Thus, simply adding the bar class at runtime is not sufficient to change the styles. In addition, in this case, Svelte sees that the bar class is not even used and thus does not generate any CSS for it.

You can use :global to make the class available everywhere, which will allow you to apply the class dynamically.

:global(.bar) {
	color : #be0000;
}

See also: https://svelte.dev/docs#component-format-style

huangapple
  • 本文由 发表于 2023年5月18日 08:32:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76277009.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定