【问题标题】:Style SVG stroke with Svelte使用 Svelte 样式化 SVG 笔画
【发布时间】:2022-02-02 18:31:48
【问题描述】:

我在 Svelte 中有以下代码,我希望使用 CSS 类名(text-error 和 text-success 而不是 #ff5722 和 #10b759)来设置笔触颜色的样式。

这可能吗?

我宁愿不在组件中定义确切的颜色,而是让主题通过 CSS 类(DaisyUI)来决定。

Svelte 新手,所有内容的最新版本。

<script>
    let isStreaming = false;

    function toggleStreaming() {
        isStreaming = !isStreaming;
    }    
</script>

<div class="someClass">
    <button on:click={toggleStreaming} class="btn {isStreaming ?
    ' text-error':
    ' text-success'}">
        <svg xmlns="http://www.w3.org/2000/svg"
             fill="none"
             viewBox="0 0 24 24"
             stroke="{isStreaming ? '#ff5722': '#10b759'}" <!-- this part -->
             class="h-6 mr-2">
            <path stroke-width="2"
                  d="{isStreaming ? 'M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636' : 'M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z'}">
            </path>
        </svg>
        {isStreaming ? 'Kill' : 'Stream'}
    </button>
</div>

【问题讨论】:

    标签: css svg tailwind-css svelte daisyui


    【解决方案1】:

    由于 Daisy UI 只是一个 Tailwind 插件,您可以像在 Tailwind 中一样执行此操作:将 stroke-current 添加到 SVG 并更改按钮的文本颜色(就像您已经在做的那样)。

    <svg ... class="h-6 mr-2 stroke-current">...
    

    这是一个使用 Daisy UI CDN 的 Svelte REPL 和您的示例,其中包含单个更改 https://svelte.dev/repl/814fd418f164491fbf97d39528cde2d3?version=3.46.3

    【讨论】:

    • 是的!这就是我所寻求的。谢谢。
    【解决方案2】:

    你可以像在按钮上一样添加类

    <... class="{isStreaming ? 'text-success' : 'text-error'}">
    

    或通过class: directive >> REPL
    ("...但是让主题通过 CSS 类来决定" 必须在类上定义笔画 - 主题中就是这种情况?否则可能会使用变量... )

    <svg
      ...
      class:text-success={isStreaming}
      class:text-error={!isStreaming}
      ...
    >
    
    <style>
        .text-success {
            stroke: #10b759;
        }
        .text-error {
            stroke: #ff5722;
        }
    </style>
    

    【讨论】:

    • 不幸的是,底层解决方案不会将颜色推迟到主题。我会硬编码&lt;style&gt; 标签中的十六进制值。例如,假设我的主题将“蓝色”指定为 text-success 值。我现在必须转到此文件并进行更改。
    • @vphilipnyc 当然,如果您要在组件中的类中设置颜色,它们不会被主题覆盖...我刚刚添加了 &lt;style&gt; 块以使 Repl 工作和表明该类必须设置 stroke 属性并询问是否是这种情况。在 @JHeth 的 REPL 中,看起来好像 .text-success 只设置了颜色属性,所以使用这个类无论如何都无法工作 - .stroke-current 确实设置了它 { stroke: currentColor;}
    • 是的,同意。感谢您的回复
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 2020-08-22
    • 2020-09-26
    • 2012-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多