【问题标题】:Svelte: Adding a class to a div doesn't add the classes CSS to divSvelte:将类添加到 div 不会将类 CSS 添加到 div
【发布时间】:2020-10-23 04:12:35
【问题描述】:

我们遇到了一个问题,点击时将类添加到 div,但类 CSS 没有添加到 div。它只是添加了类。

<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>

创建了一个 REPL 来查看它。任何解释或解决方案表示赞赏

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

【问题讨论】:

  • 您指的是一个类,但只给出了
    和“id”。尝试向
    添加一个类

标签: css class onclick svelte sapper


【解决方案1】:

Svelte 编译器删除了未使用的 CSS 规则,它只看到组件标记中实际使用的类。

必须这样做才能确定组件的 CSS 范围,因为范围设置通过将唯一生成的类添加到具有匹配(范围)CSS 规则的所有组件元素来工作。

在您的情况下,编译器在标记中看不到 blueText 类,如“未使用的 CSS 选择器”警告所示。

使用 Svelte 条件类具有编译器知道的条件(和作用域)类:

<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>

或者,使用快捷语法:

<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>

如果您不希望条件类被限定范围,您可以简单地将其设为 :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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 2017-10-23
    • 2012-10-26
    • 2012-08-04
    • 2013-01-07
    • 2019-08-12
    • 1970-01-01
    相关资源
    最近更新 更多