Html 如何将颜色应用于 SVG 文本元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17466707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:45:24  来源:igfitidea点击:

How to apply a color to a SVG Text element

htmlcsstextsvg

提问by Bastiaan Linders

Okay... I'm going nuts over here. I've started experimenting with SVG. Working with SVG and applying CSS classes to it works like a charm. I just cant figure out what i'm doing wrong, but i just cant get the class to work on a svg text element. I've stripped it all the way down and this is what i got:

好吧……我要疯了。我已经开始尝试使用 SVG。使用 SVG 并将 CSS 类应用于它就像一种魅力。我只是不知道我做错了什么,但我只是无法让班级在 svg 文本元素上工作。我已经把它彻底剥离了,这就是我得到的:

<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>Playground</title>
</head>
<body>
    <style type="text/css">
        .mainsvg {
            height: 320px;
            border: 1px solid red;
            width: 400px;
        }
        .caption {
            color: yellow;
        }
    </style>
    <h2>SVG - Sandbox</h2>
    <div>
        <svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="mainsvg">
            <text x="65" y="40" class="caption">Fact</text>
        </svg>
    </div>
</body>
</html>

According to http://www.w3.org/TR/SVG/styling.html#ClassAttributethis should work...

根据http://www.w3.org/TR/SVG/styling.html#ClassAttribute这应该工作......

Any hints/tips on what to change, or an alternative?

关于更改内容或替代方法的任何提示/提示?

回答by Robert Longson

Setting the class is correct but the CSS color property has no effect on SVG. SVG uses filland strokeproperties. In your case you probably just need to change color to fill. This displays yellow text for me in Firefox.

设置类是正确的,但 CSS 颜色属性对 SVG 没有影响。SVG 使用填充描边属性。在您的情况下,您可能只需要更改颜色即可填充。这在 Firefox 中为我显示黄色文本。

<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>Playground</title>
</head>
<body>
    <style type="text/css">
        .mainsvg {
            height: 320px;
            border: 1px solid red;
            width: 400px;
        }
        .caption {
            fill: yellow;
        }
    </style>
    <h2>SVG - Sandbox</h2>
    <div>
        <svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="mainsvg">
            <text x="65" y="40" class="caption">Fact</text>
        </svg>
    </div>
</body>
</html>