【问题标题】:Is it possible to use css variables inside inline svg?是否可以在内联 svg 中使用 css 变量?
【发布时间】:2019-05-27 02:52:45
【问题描述】:

我正在为网站编写用户样式,我使用 css 变量进行用户配置。我正在尝试使用带有变量的内联 svg 来创建一个设置为用户首选强调色的复选标记。但这似乎不起作用。

在提供的代码中,我只是卡在了 var 函数中,但我也尝试将笔画的颜色设置为 currentColor,并将元素的颜色设置为变量。设置掩码和背景颜色工作,但我想要一个“纯内联 svg”解决方案。

.checkmark {
    background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="12">\
    <path fill="none" stroke="var(--ColAccent)" stroke-width="3" d="M1.99609375 5.7835338l3.70287382 3.7028738L14.1853752 1"/>\
</svg>');
}

复选标记应为强调色。当我通过简单地放入 var() 来设置它时,它不起作用并且是透明的。有趣的是,当使用 currentColor 方法时,描边是黑色的。

【问题讨论】:

    标签: css svg css-variables inline-svg


    【解决方案1】:

    这是有效的:

    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="12" style="--ColAccent:red">
        <path fill="none" style="stroke:var(--ColAccent)" stroke-width="3" d="M1.99609375 5.7835338l3.70287382 3.7028738L14.1853752 1"/>
    </svg>

    这是工作:

    background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='--ColAccent:red' width='16' height='12'%3E%3Cpath fill='none' style='stroke:var(--ColAccent)' stroke-width='3' d='M1.99609375 5.7835338l3.70287382 3.7028738L14.1853752 1'/%3E%3C/svg%3E%0A")'
    

    为了解决您的问题,我会使用 javascript:

    let _checkmark = document.querySelector(".checkmark");
    let ColAccent = _checkmark.style.getPropertyValue("--ColAccent");
    _checkmark.style.backgroundImage = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='12'%3E%3Cpath fill='none' stroke='${ColAccent}' stroke-width='3' d='M1.99609375 5.7835338l3.70287382 3.7028738L14.1853752 1'/%3E%3C/svg%3E%0A")`
    .checkmark {
      width:100px;
      height:100px;
      border:1px solid;
    }
    &lt;div class="checkmark" style="--ColAccent:skyBlue" &gt;&lt;/div&gt;

    【讨论】:

    • 我正在创建一个用户样式,我不能真正使用 javascript
    【解决方案2】:

    我不认为可以直接在 inline svg 中使用 css 变量,因为 inline svg 不是直接在 DOM 中,并且您不能使用 css 来定位它(即,无法定位 svg来自.checkmark 类。唯一的其他选择是使用javascript getPropertyValue 获取css 变量--ColAccent 的值,并使用它创建具有有效颜色名称(即red)或URI 编码的url 字符串stroke 的颜色值(即%23f00 解码为#f00)。由于不能使用javascript,我想不出其他方法。

    【讨论】:

      猜你喜欢
      • 2014-01-13
      • 2018-08-01
      • 2023-03-26
      • 1970-01-01
      • 2018-02-24
      • 2019-01-25
      • 1970-01-01
      • 2018-12-02
      • 2016-06-13
      相关资源
      最近更新 更多