html - SVG 堆栈在 Chrome 中不起作用(webkit)

标签 html css google-chrome svg webkit

我一直在探索将 SVG 用于我一直在构建的最新网站 - 有点落伍了,所以我想 catch 来。我最初设置我的文件类似于我做普通 Sprite 的方式。虽然这很有效,但当您想利用调整矢量大小然后尝试在文档中找到新的背景位置时,它看起来确实有点笨拙!

在做了一些研究之后,我想到了通过图层堆叠它的想法 - 这很有意义。在兴奋并成功完成此操作后,我看到一些帖子说这并非在所有浏览器中都支持 - 典型情况。

https://code.google.com/p/chromium/issues/detail?id=128055#c6

这里有一个很棒的教程,用于在单个文件中堆叠 SVG 图像,以及一些针对不支持它的浏览器的解决方法:http://hofmannsven.com/2013/laboratory/svg-stacking/

虽然这工作正常,但是否有替代方法来节省编写所有这些额外代码和回退?

最佳答案

考虑一下之后,我决定可以利用 Apache 服务器,看看是否可以简单地将我需要的内容注入(inject)到文档中。最后的结果?在所有浏览器中完美运行:)

首先,我在 .htaccess 文件中添加了一些代码来捕获所有 .svg 请求

RewriteRule ^(.*)\.svg$ /{path-to-file}/svg.php [L]

然后我写了几行来处理目标层并将其注入(inject)到文件中

(更新)添加了名为target-fill 的新变量,以允许在需要时动态更改形状的填充颜色

<?php
// Set the SVG header
header('Content-Type: image/svg+xml');
$queryString = Array();
if(isset($_SERVER['QUERY_STRING'])) $queryString = explode('&', $_SERVER['QUERY_STRING']);
// Get target from the query string
$target = $queryString[0];
    // Get a fill alternative if available and valid
if(isset($queryString[1]) && hexdec($queryString[1]) !== false) {
    $targetFill = '#' . $queryString[1];
} else {
    $targetFill = '';
}
// Validate the target - this is your ID in the SVG file
$validTargets = Array('Camera', 'Layer_1');
if(!in_array($target, $validTargets)) $target = false;
// Get contents of the file - tweak this depending on where you have saved this file to relative to the root of your website
$filename = '../..' . $_SERVER['REDIRECT_URL'];
// Get the contents of the file
$contents = file_get_contents($filename);
// Replace the target with the valid target above
// - doing it this way rather than echoing the target in the SVG file as it seemed like a security risk
if($target) $contents = str_replace('g:target', 'g#' . $target, $contents);
// Replace the fill colour if available
$contents = str_replace('target-fill', $targetFill, $contents);
// Output the amended SVG file
echo $contents;

靠近 SVG 顶部的是堆叠代码,用于隐藏我们不想显示的内容并打开我们所做的事情

<defs>
    <style>
      svg g { display: none }
      svg g:target, svg g:target g { display: inline }
      svg g:target * { fill: target-fill; }
    </style>
</defs>

就是这样。所以现在不要调用你的 SVG 文件(也可以作为背景图像):

<img src="images/svg-file.svg#Camera">

你会这样做

<img src="images/svg-file.svg?Camera">

这样做的好处是,如果不支持 SVG,您现在还可以根据用户代理进行一些进一步的检查,以完全返回一个替代文件。

(更新)如果需要,您现在还可以表达第二个参数来更改填充颜色。像这样使用它:

<img src="images/svg-file.svg?Camera&cc0000">

希望这对其他人有帮助。

关于html - SVG 堆栈在 Chrome 中不起作用(webkit),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23600302/

相关文章:

javascript - shadowbox 在新页面上打开图像

javascript - 转义我的 HTML 字符

javascript - 谷歌地图 Bootstrap 3

php - 如何在wordpress自定义中添加颜色选项

javascript - 无需在 Chrome 中右键单击即可检查元素

html - <td> 间距在 Chrome 中不起作用

javascript - 音频 HTML5 自动播放 WebWorks

css - 如何在JSP上打印账单

javascript - 图像淡入然后文本不起作用

css - z-index chrome 错误