英文:
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 <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?
See the example below that reproduces this behavior:
<script>
import { onMount } from "svelte";
function addClass() {
document.getElementById('example').classList.add('foo');
// class is added, but nothing appears to happen
}
</script>
<div id="example">Hi</div>
<button on:click={addClass}>Add foo class</button>
<style>
.foo {
color : #be0000;
}
</style>
答案1
得分: 1
<style>
元素中声明的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 <style>
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论