Pau*_*ast 4 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>
Run Code Online (Sandbox Code Playgroud)
这作为一个<object>元素(<object type="image/svg+xml" data="img/svg/cross.svg#ff0000"></object>)完全正常,但作为一个img或css 失败background-image.
我怎样才能将这个工作作为CSS background-image?
出于安全原因,SVG中用作HTML映像的动态行为被禁用.原因很明显 - 您可以使用来自不同域的SVG图像,并且不希望它在文档的上下文中运行JavaScript代码.因此,用作HTML图像的SVG基本上都是静态的.有关http://www.schepers.cc/svg/blendups/embedding.html的更多详细信息(感谢@ RobertLongson提供此链接).
Firefox中有一个解决方法:如果你有内联 SVG代码(可以隐藏),你可以使用filterCSS属性从该SVG代码中使用过滤器.根据您要实现的目标,这可能是一个相当强大的工具.根据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>'));
Run Code Online (Sandbox Code Playgroud)
Base64 插件可在此处找到: URL- or Base64-encode strings in Compass/SASS
| 归档时间: |
|
| 查看次数: |
4491 次 |
| 最近记录: |