javascript - 在背景图像 svg 中使用 JavaScript

标签 javascript css svg

我有一个 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/

相关文章:

JavaScript 正则表达式将 '+ve' 替换为 'positive' 不起作用

javascript - 如果函数处于错误情况下,我该如何停止执行?

html - CSS 中的 Clip-Path Inset 在 Chrome 中不起作用

javascript - HTML5 我可以将 <img> 与 <source> 一起使用吗

svg - 为什么 SVG 文件在 Mac 上应该有一个空格?

javascript - jQuery fadeIn(), fadeOut() 导致性能急剧下降

javascript - 如何访问特定的 Web 元素 Selenium Python

javascript - 使用 Axios (React) 从 API 获取数据时出现“Access-Control-Allow-Origin”错误

javascript - 在 Vue JS 3 的 CSS 类中使用模板变量

css - 如何从响应式网站创建电子邮件模板?