javascript - html 中的内联 svg - 如何优雅地降级?

标签 javascript html svg

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

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

具有讽刺意味的是,在 IE8 和更低版本中使用条件注释很容易处理这个问题。

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

是否有更好的方法(更好的 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>

最佳答案

对于 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/

关于javascript - html 中的内联 svg - 如何优雅地降级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10469457/

相关文章:

javascript - Highcharts 上特定点的自定义工具提示数据

javascript - 在 HTML 中使用带有多个条件的 ng-if

javascript - 将 chrome.tabcapture.capture 转换为音频文件?

html - 居中 div 旁边的 DIV

javascript - 为什么 this.selectedIndex 在 IE7 上不能用于 <select> 标签?

javascript - xhr 发送 base64 字符串并在服务器中将其解码为文件

javascript - 将 div 移动到 svg map 上的坐标

javascript - 获取具有特定类的每个 "rect"的 x Position 属性

javascript - 垂直导航栏 ​​- Onclick 功能不起作用

javascript - 无法绑定(bind)触发器单击 svg 路径元素