css - 样式内嵌 css 的 svg

标签 css svg

.player
{
    background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'><line x1='1' y1='1' x2='9' y2='9' stroke='red'/><line x1='1' y1='9' x2='9' y2='1' stroke='red'/></svg>");
    width: 100%;
    height: 100%;
    display: inline-block;
}
.one
{
    fill: black;
}
.two
{
    stroke: white;
}

具有 player 类的元素将有一个 svg 背景图像。如果元素同时具有 playeronetwo 类,是否可以更改 svg 的样式(如果它是内联的)所以?如果没有,我将如何通过上课来进行简单的颜色更改?理想情况下,我不想在 html 中引入任何更多标记并阻止对这么小的 svg 文件进行 http 访问。

最佳答案

正如 Douglas 所写,您只能使用内联“src”设置 IMG 元素的样式。

我使用这种技术:

将普通图像与您的 SVG 路径一起使用:

<img src="my.svg" alt="">

使用 JavaScript (jQuery) 将“src”转换为内联样式:

$('img').each(function(){
    var $img = jQuery(this);
    var imgID = $img.attr('id');
    var imgClass = $img.attr('class');
    var imgURL = $img.attr('src');

    jQuery.get(imgURL, function(data) {
        // Get the SVG tag, ignore the rest
        var $svg = jQuery(data).find('svg');

        // Add replaced image's ID to the new SVG
        if(typeof imgID !== 'undefined') {
            $svg = $svg.attr('id', imgID);
        }
        // Add replaced image's classes to the new SVG
        if(typeof imgClass !== 'undefined') {
            $svg = $svg.attr('class', imgClass+' replaced-svg');
        }

        // Remove any invalid XML tags as per http://validator.w3.org
        $svg = $svg.removeAttr('xmlns:a');

        // Replace image with new SVG
        $img.replaceWith($svg);

    }, 'xml');
});

使用 CSS 设置 SVG 的样式:

path {
    fill: #f00;
}

完成。

关于css - 样式内嵌 css 的 svg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31710057/

相关文章:

javascript - 在 Chrome 和 Firefox 上获取 C9 应用程序的解析错误。不确定如何解决

jQuery/CSS 图像缩放 - 屏幕截图?

javascript - 在鼠标悬停的 SVG 路径周围添加区域

javascript - snap SVG 中的 g() 是什么

javascript - 使用 mathjax 或类似工具将 Latex/MathML 转换为 SVG 或图像?

javascript - 通过单击关闭模式弹出窗口

html - 将按钮添加到列表组 Bootstrap 上的链接项

javascript - 通过 Javascript 单击时 PrimeFaces 单选按钮样式不更新

svg - 如何围绕椭圆制作 SVG 圆动画

javascript - D3 鼠标事件——单击和拖动结束