简体   繁体   English

Svelte:将 class 添加到 div 不会将类 CSS 添加到 div

[英]Svelte: Adding a class to a div doesn't add the classes CSS to div

We are having a problem where on click is adding a class to a div but the classes CSS doesn't get add to the div.我们遇到了一个问题,点击时将 class 添加到 div 但类 CSS 没有添加到 div。 It just adds the class.它只是添加了 class。

<script>
    function handleClick() {
        document.getElementById('text').classList.add('blueText')
    }
</script>
<style>
    .blueText{
        color:blue;
    }
</style>
<button on:click={handleClick}>
    Click me
</button>
<div id="text">
        Text
</div>

Created a REPL to see it as well.创建了一个 REPL 来查看它。 Any explanations or solutions appreciated任何解释或解决方案表示赞赏

https://svelte.dev/repl/85554a5f15134a5694c36fc4f4782029?version=3.23.2 https://svelte.dev/repl/85554a5f15134a5694c36fc4f4782029?version=3.23.2

Svelte compiler removes unused CSS rules, and it only see classes that are actually used in the component's markup. Svelte 编译器删除了未使用的 CSS 规则,它只看到组件标记中实际使用的类。

It has to do this to be able to scope your component's CSS, because scoping works by adding a unique generated class to all the component's elements that have a matching (scoped) CSS rule. It has to do this to be able to scope your component's CSS, because scoping works by adding a unique generated class to all the component's elements that have a matching (scoped) CSS rule.

In your case, the compiler doesn't see the blueText class in the markup, as indicated by the "Unused CSS selector" warning.在您的情况下,编译器在标记中看不到blueText class,如“未使用的 CSS 选择器”警告所示。

Use Svelte conditional class to have a conditional (and scoped) class that the compiler is aware of:使用 Svelte 条件 class 来获得编译器知道的条件(和范围) class:

<script>
    let isBlue = false
    
    function handleClick() {
        isBlue = !isBlue
    }
</script>

<style>
    .blueText {
        color: blue;
    }
</style>

<button on:click={handleClick}>
    Click me
</button>

<div class:blueText={isBlue}>
    Text
</div>

Or, with shortcut syntax:或者,使用快捷语法:

<script>
    let blueText = false
    
    function handleClick() {
        blueText = !blueText
    }
</script>

<style>
    .blueText {
        color: blue;
    }
</style>

<button on:click={handleClick}>
    Click me
</button>

<div class:blueText>
    Text
</div>

If you don't want your conditional class to be scoped, you can simply make it :global -- Svelte compiler never trims global rules, it doesn't need to.如果你不希望你的条件 class 被限定,你可以简单地使它:global - Svelte 编译器从不修剪全局规则,它不需要。

<script>
    function handleClick() {
        document.getElementById('text').classList.add('blueText')
    }
</script>
<style>
    :global(.blueText) {
        color: blue;
    }
</style>
<button on:click={handleClick}>
    Click me
</button>
<div id="text">
    Text
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM