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

Chr*_*haw 9 html javascript svg

请参阅下面的代码 - 我试图在我的网站中包含内联svg.我遵循一个巧妙的建议,使用svg开关元素,以便它在旧浏览器上优雅地降级.想法是支持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>
Run Code Online (Sandbox Code Playgroud)

Alo*_*hci 5

text对于仅支持CSS的解决方案,这是针对IE8及更早版本之外的浏览器(需要基于JS的shiv来识别元素.)的想法,

<!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>
Run Code Online (Sandbox Code Playgroud)

这里的想法是,在支持SVG浏览器内嵌,通过将SVG元素融入"http://www.w3.org/2000/svg"命名空间,然后可以在CSS来解决这样做.

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

JSFiddle http://jsfiddle.net/rGjKs/