简体   繁体   English

是否可以在内联 svg 中使用 css 变量?

[英]Is it possible to use css variables inside inline svg?

I am writing a userstyle for a website, I use css variables for configuration by the user.我正在为网站编写用户样式,我使用 css 变量进行用户配置。 I am trying to use inline svg with a variable in it to create a checkmark set to the user's preferred accent color.我正在尝试使用带有变量的内联 svg 来创建设置为用户首选强调色的复选标记。 But it doesn't seem to work.但它似乎不起作用。

In the code provided I just jammed in the var function, but I've also tried setting the color of the stroke to currentColor and setting the color of the element to the variable.在提供的代码中,我只是在 var 函数中卡住了,但我也尝试将笔触的颜色设置为 currentColor 并将元素的颜色设置为变量。 Setting the mask and background-color work but I want a "pure inline svg" solution.设置遮罩和背景颜色有效,但我想要一个“纯内联 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>');
}

The checkmark should be accent color.复选标记应该是强调色。 When I set it by simply putting in the var() it doesn't work and is transparent.当我通过简单地放入 var() 来设置它时,它不起作用并且是透明的。 Interestingly, when using the currentColor method, the stroke is black.有趣的是,在使用 currentColor 方法时,笔触是黑色的。

This is working:这是有效的:

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

This is not working:不是工作:

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")'

For a solution to your problem I would use javascript:为了解决您的问题,我将使用 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; }
 <div class="checkmark" style="--ColAccent:skyBlue" ></div>

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

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

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