繁体   English   中英

在background-image svg中使用JavaScript

[英]Using JavaScript in a background-image 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失败background-image

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

出于安全原因 ,SVG中用作HTML映像的动态行为被禁用 原因很明显 - 您可以使用来自不同域的SVG图像,并且不希望它在文档的上下文中运行JavaScript代码。 因此,用作HTML图像的SVG基本上都是静态的。 有关http://www.schepers.cc/svg/blendups/embedding.html的更多详细信息(感谢@ RobertLongson提供此链接)。

Firefox中有一个解决方法:如果你有内联 SVG代码(可以隐藏),你可以使用过滤filter CSS属性从该SVG代码中使用filter 根据您要实现的目标,这可能是一个相当强大的工具 根据MDN Chrome和Safari也应该支持这一点,但我不确定他们会这样做。

我找到了一个适合我的解决方案。 我也在使用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插件位于: Compass / SASS中的URL-或Base64-编码字符串

暂无
暂无

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

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