ITeye博客

icon font VS svg font

mutongwu · 2015-05-14 15:21 · JavaScript · CSS · mobile · Web前端 · Markdown

关于字体图标和SVG图标,CSS TRICK网站有较好的说明。

https://css-tricks.com/icon-fonts-vs-svg/ 总的来讲:

**1. 字体图标浏览器支持多一点。(IE6+) 2. SVG显示效果好一些,更多的CSS控制(例如:支持图标颜色渐变),制作相对简单些。(IE9+) **

需要补充的是,SVG有以下缺点:

  1. 对于IE浏览器,SVG文件需要 inline到HTML页面。
  2. 对于外联的SVG文件,测试中发现,不支持跨域使用,即便 svg文件做了CROS头部设置。

针对以上2个问题,解决的方式,就是额外加载外联svg文件,并把它插入到HTML页面里面。

测试页面 test.html,假设地址为 http://shawn.b.com:5678/test.html



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes"/>
<meta name="apple-mobile-web-app-status-bar-style" content="black"/>
<meta content="telephone=no" name="format-detection" />  
<!-- script src="svg4everybody.js"></script -->
<title>SVG sprite</title>
<!-- link type="text/css" href="svg-symbols.css" rel="stylesheet"/ -->
<style>
	.icon{width:32px;height:32px;}
</style>
</head>
<body>
	<div id="layout-wrapper">
		<svg class="icon">
			<use xlink:href="http://shawn.a.com:1234/svgdefs.svg#icon-bin"></use> <!-- 跨域情况下,图标是不能正确显示的 -->
		</svg>
	</div>
	
	<input type="button" value="ajax加载" onclick="loadExternal()"/>
	<script>
	function loadExternal(){
		var xhr = new XMLHttpRequest();
		try{
			//跨域了。
			xhr.open('GET', "http://shawn.a.com:1234/svgdefs.svg");
		}catch(e){
			xhr = new XDomainRequest(); //IE9
			xhr.open('GET', "http://shawn.a.com:1234/svgdefs.svg");
		}
		
		
		xhr.onload = function(){
			var div = document.createElement("div");
			div.innerHTML = xhr.responseText;
			document.body.appendChild(div);
			
			var uses = document.getElementsByTagName("use");
			
			for(var i=0,len = uses.length; i < len; i++){
				var url = uses[i].getAttribute('xlink:href').split('#');
				var url_root = url[0];
				var url_hash = url[1];
				uses[i].setAttribute('xlink:href','#' + url_hash);
			}
		};

		xhr.send();
	}
	
	</script>
</body>
</html>

https://css-tricks.com/svg-use-external-source/ https://css-tricks.com/svg-sprites-use-better-icon-fonts/

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。