在background-image svg中使用JavaScript

时间:2013-05-30 13:45:32

标签: javascript css svg

我有一个SVG(十字架),它根据使用JavaScript提供给SVG网址的哈希值来改变线条的颜色。

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <line x1="0" y1="0" x2="100%" y2="100%" stroke="black" stroke-width="1" />
    <line x1="100%" y1="0" x2="0" y2="100%" stroke="black" stroke-width="1" />

    <script>
        if (window.location.hash) {
            document.getElementsByTagName('line')[0].setAttribute('stroke', location.hash);
            document.getElementsByTagName('line')[1].setAttribute('stroke', location.hash);
        }
    </script>
</svg>

这作为<object>元素(<object type="image/svg+xml" data="img/svg/cross.svg#ff0000"></object>)完全正常,但作为img或css background-image失败。

如何将此工作作为CSS background-image

2 个答案:

答案 0 :(得分:6)

用作HTML图像的SVG中的动态行为是disabled for security reasons。原因很明显 - 您可以使用来自不同域的SVG图像,并且不希望它在文档的上下文中运行JavaScript代码。因此,用作HTML图像的SVG基本上都是静态的。有关http://www.schepers.cc/svg/blendups/embedding.html的更多详情(感谢@ RobertLongson获取此链接)。

Firefox中有一种解决方法:如果你有内联 SVG代码(可以隐藏),你可以使用filter CSS property从该SVG代码中使用过滤器。根据您要实现的目标,这可能相当powerful tool。根据MDN Chrome和Safari也应该支持这一点,但我不确定他们是否支持。

答案 1 :(得分:4)

我自己找到了一个适合我的解决方案。 我也在使用Sass,有了它我找到了一个base64编码插件。 有了它,我可以在我的CSS中编写svg,然后将其编码为base64。我也可以使用变量。 SASS代码现在看起来像这样:

background: url('data:image/svg+xml;base64,'
                + base64Encode('<svg xmlns="http://www.w3.org/2000/svg"><line x1="0" y1="0" x2="100%" y2="100%" stroke="#{$color-line}" stroke-width="1" /><line x1="100%" y1="0" x2="0" y2="100%" stroke="#{$color-line}" stroke-width="1" /></svg>'));

这里有base64插件: URL- or Base64- encode strings in Compass/SASS