我有一个 SVG(十字),它根据使用 JavaScript 提供给 SVG url 的散列更改线条的颜色。
<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
?
最佳答案
用作 HTML 图像的 SVG 中的动态行为是 disabled for security reasons .原因很明显——您可以使用来自不同域的 SVG 图像,并不真的希望它在您的文档上下文中运行 JavaScript 代码。所以用作 HTML 图像的 SVG 本质上总是静态的。关于 http://www.schepers.cc/svg/blendups/embedding.html 有更多详细信息(感谢@ RobertLongson 提供此链接)。
Firefox 中有一个解决方法:如果您有内联 SVG 代码(可以隐藏),您可以使用来自该 SVG 代码的过滤器,使用 filter
CSS property .根据您要实现的目标,这可能是 powerful tool .根据 MDN,Chrome 和 Safari 也应该支持这一点,但我不确定它们是否支持。
关于javascript - 在背景图像 svg 中使用 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16837960/