在考虑了一下之后,我决定我可以利用 Apache 服务器,看看我是否可以简单地将我需要的内容注入到文档中。最终结果?在所有浏览器中都能完美运行 :)
首先,我在 .htaccess 文件中添加了一些代码来捕获所有 .svg 请求
RewriteRule ^(.*)\.svg$ /{path-to-file}/svg.php [L]
然后我写了几行来处理目标层并将其注入文件中
(更新)添加了名为 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">
希望这对其他人有帮助。