intml svg in html - 如何优雅地降级?

时间:2012-05-06 09:20:18

标签: javascript html svg

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

它的效果非常好......除了我的svg(乐谱)必然包含文本元素,它们被旧浏览器渲染(以及外部对象)。

具有讽刺意味的是,在IE8及以下版本中使用条件注释很容易处理。

对于其他较旧的浏览器,我在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>

1 个答案:

答案 0 :(得分:5)

这是一个关于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中进行寻址。 / p>

在Firefox 12,IE9,Chrome 18 Opera 11.6(显示SVG)以及Firefox 3.6和Safari 5.0中进行了测试,显示了后退。

JSFiddle http://jsfiddle.net/rGjKs/