gpt4 book ai didi

css - 如何以跨浏览器一致的方式使用 svg 模式?

转载 作者:技术小花猫 更新时间:2023-10-29 11:13:04 27 4
gpt4 key购买 nike

我希望 SVG 图像(预渲染,但在 svg 标签中插入 js,以允许进行一些进一步的操作)能够使用预定义的模式,使用“pattern”标签。听起来很简单,不是吗?好吧,事实证明 Chrome(Webkit?)的行为与任何其他浏览器都有些不同,现在我不确定实现这一点的最佳方法是什么。

我的 svg 看起来像这样:

<svg>
<defs>
<pattern id="specialPattern">...</pattern>
</defs>
<path class="special"></path>
</svg>

并且我希望具有类 special 的路径以“pattern”作为填充。

尝试一:适用于 Chrome,不适用于 FF 或 Opera

我的第一次尝试是简单地将其放入我的 CSS 中:

 .special { fill:url("#specialPattern");}

这实际上适用于 Chrome,但当您考虑它时,它可能不应该。我试过的其他浏览器将此 url 解释为相对于它所在的文件(css 文件),which makes more sense .

尝试二:适用于 FF 和 Opera,不适用于 Chrome

下一次尝试:提供模式的绝对 URL。

 .special { fill:url("//example.com/styles/svgWithStyleDeclaration.svg#specialPattern");}

虽然这在 FF 和 Opera 中按预期工作,但 Chrome 现在会重置填充(我不知道它实际上在哪里寻找那种样式)

尝试三:作品,有点

在 SVG 中内联样式似乎无处不在:style="fill:url('#specialPattern')"

虽然我猜这是内容和表示之间的界限模糊的情况,但至少在我的情况下,将样式声明保留在其他地方会更好(尤其是因为这会使我的 SVG 需要更大) )

尝试四:可行(?)但很脏

我没有测试过很多浏览器,所以我不确定它的防水性如何,但在我看来使用 css hack 来检测 webkit 浏览器会起作用:

@media screen and (-webkit-min-device-pixel-ratio:0) {
.special {fill: url("#specialPattern");}
}
.special { fill:url("//example.com/styles/svgWithStyleDeclaration.svg#specialPattern");}

现在,必须有更优雅的方法来解决这个问题。应该怎么做?

编辑:事实证明 IE 在此处的行为与 Chrome 类似,因此您还需要确保 IE<=9 具有“fill: url(#specialPattern)”

最佳答案

这是我为操纵图案和 mask 而制作的 Fiddle。这是一个 svg xml 格式的评分显示,我希望能够在其中使用评分栏的百分比。

fiddle :http://jsfiddle.net/cnLHE/296/

通过将最后一行更改为“width="50",然后按运行,您可以看到评级栏调整大小。

<svg width="100%" height="100%" viewBox="0 0 100 20" version="1.1">
<defs>
<pattern id="pattern1" x="0" y="0" width="20" height="20"
patternUnits="userSpaceOnUse" >
<circle cx="10" cy="10" r="5" style="fill:white" />
</pattern>
<pattern id="pattern2" x="0" y="0" width="20" height="20"
patternUnits="userSpaceOnUse" >
<circle cx="10" cy="10" r="9" style="fill:white" />
<circle cx="10" cy="10" r="7" style="fill:black" />
</pattern>
<mask id="mask1" x="0" y="0" width="100" height="20" >
<rect x="0" y="0" width="100" height="20"
style="stroke:none; fill: url(#pattern2)"/>
</mask>
<mask id="mask5" x="0" y="0" width="100" height="20" >
<rect x="0" y="0" width="100" height="20"
style="stroke:none; fill: url(#pattern1)"/>
</mask>
</defs>1<rect x="0" y="0" width="500" height="20" fill="url(#pattern2)" style="fill:#2498c7; mask: url(#mask1)"/>
<rect x="0" y="0" width="50" height="20" style="fill:#2498c7; mask: url(#mask5)"/>

</svg>

我没有遇到任何跨浏览器问题,但是,我确实遇到了 SVG 在网格布局中间歇性消失的问题。在页面中有多个实例的 webkit 中,它们并不总是显示。

可在 css-tricks 获取更多信息:http://css-tricks.com/using-svg/

关于css - 如何以跨浏览器一致的方式使用 svg 模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20459685/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com