【问题标题】:inline svg in html - how to degrade gracefully?html中的内联svg - 如何优雅地降级?
【发布时间】:2012-05-15 05:10:39
【问题描述】:

请参阅下面的代码 - 我正在尝试在我的网站中包含内联 svg。我正在关注a neat suggestion 使用 svg 开关元素,以便它在旧浏览器上优雅地降级。这个想法是支持 svg 的浏览器使用 switch 块中的第一个元素;那些不忽略所有 svg 标签而只显示埋在 switch 块的第二个元素(即 foreignobject 标签)中的 img。

它工作得非常好......除了我的 svg(它是乐谱)必须包含文本元素并且它们被旧浏览器呈现(以及外来对象)。

具有讽刺意味的是,在 IE8 及更低版本中使用条件 cmets 很容易处理此问题。

对于其他较旧的浏览器,我在 foreignobject 中有一个 javascript 解决方法,它重新定义了 svg 文本的类。它有效......但感觉就像一个真正的黑客。

有没有更好的方法来做到这一点(更好的 javascript、css 解决方案、另一种处理 svg 文本的方法......)?

这里是代码的基本内容:

<html>
<head>

<!-- this deals with elements using the svgtext class in old IE browsers -->
<!--[if lte IE 8]>
<style type="text/css">
.svgtext { display: none; }
</style>
<![endif]-->
<style type="text/css">
.donotdisplay { display: none; }
</style>

</head>
<body>

<svg ...>
<switch>
<g>
<!-- the svg goes here -->
<text class="svgtext">this gets rendered unless I deal with it</text>
</g>
<foreignObject ...>
<script type="text/javascript">
window.onload=function(){
  var inputs=document.getElementsByTagName('text');
  for(i=0;i<inputs.length;i++){
    inputs[i].className='donotdisplay';
  }
}
</script>
<!-- the replacement img tag goes here -->
</foreignObject>
</switch>
</svg>

</body>
</html>

【问题讨论】:

  • 我会看看 RaphaelJS,以防它提供特征检测 - 或者也许是 Modernizr。也没用过,但都值得一试。
  • 除了不支持 SVG 的 IE8 之外,您还尝试支持哪些其他旧浏览器?
  • @halfer - Modernizr 将在整个文档中添加 svgno-svg 类,可以在代码中或使用 CSS 选择器进行检查。它不会自动解决问题,但很容易检查。
  • @TimMedora - 很酷,这样就可以了。有时间一定要试一试!
  • @TimMedora - 谢谢,Modernizr 听起来就像这份工作。

标签: javascript html svg


【解决方案1】:

这是一个针对 IE8 和更早版本以外的浏览器(需要基于 JS 的 shiv 来识别 text 元素)的想法,用于仅使用 CSS 的解决方案,

<!DOCTYPE html>
<html>
  <head>
    <title>Test Case</title>

<!--[if lte IE 8]>
    <script type="text/javascript">
      document.createElement("text");
    </script>
<![endif]-->

    <style type="text/css">
      @namespace svg "http://www.w3.org/2000/svg";
      text { display: none; }
      svg|text { display: inline; }
    </style>
  </head>
  <body>

    <svg>
      <switch>
        <g>
          <circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>
          <text x="20" y="120">this gets rendered unless I deal with it</text>
        </g>
        <foreignObject>
          <p>Use an SVG capable browser</p>
        </foreignObject>
      </switch>
    </svg>

  </body>
</html>

这里的想法是支持 SVG 内联的浏览器通过将 SVG 元素放入“http://www.w3.org/2000/svg”命名空间来实现,然后可以在 css 中对其进行寻址。

在显示 SVG 的 Firefox 12、IE9、Chrome 18 Opera 11.6 以及显示回退的 Firefox 3.6 和 Safari 5.0 中测试。

JSFiddle http://jsfiddle.net/rGjKs/

【讨论】:

  • 谢谢!也适用于显示回退的较旧的 android 浏览器。 Modernizr 库看起来很有趣,但我非常喜欢这个解决方案,因为它更简单并且避免了 javascript。
  • 管道字符| 是什么意思,在svg|text 中?
  • @Sathvik - 它只是命名空间前缀和元素本地名称之间的分隔符。或多或少等同于 XML 中的“:”(冒号)字符。
猜你喜欢
  • 2017-08-12
  • 2023-04-01
  • 2012-07-01
  • 2011-08-29
  • 1970-01-01
  • 2010-11-13
  • 1970-01-01
  • 2011-02-18
  • 2014-09-30
相关资源
最近更新 更多