LoginSignup
7
7

More than 5 years have passed since last update.

IE8以下で表示用ライブラリなしでSVGを使うためにやった荒業

Posted at

自分用のメモ。

IE8以下ではimg要素のsrcにsvgを指定できない

出来ないんですよね。かと言ってコンパチする方法が結構手間っぽい
参考:http://osumituki.com/web-front/programs/164.html

サーバーサイドでクライアント判定してタグ出し分けするほうが綺麗で確実な感じもするけど、そういうわけにも行かなかったので荒業を使うことにした。

imgタグに.svgが指定されているとき、object要素にすげ替えてしまおう

という、荒業を試してみることにしました。

if(/* IE8以下なら */) {
$('img[src$=".svg"]').each(function(){
    $(this).after('<object data="'+$(this).attr('src')+'" type="image/svg+xml" width="'+$(this).attr('width')+'" height="'+$(this).attr('height')+'" alt="'+$(this).attr('alt')+'" class="'+$(this).attr('class')+'" style="pointer-events: none;overflow:hidden;height:'+$(this).attr('height')+'px;width:'+$(this).attr('width')+'px"></object>');
    $(this).remove();
});
}

なお、createElementでobjectタグを作って挿入してもうまくいかず、
上記の様な書き方をするとうまくいきました・・・原因が何なのかよくわかりません:;(∩´﹏`∩);:

得られた結果は見た目は問題がない状態に保持させられましたが、SVG中のviewBox指定とHTMLで指定しているサイズがあってないとスクロールバーが出てきてしまうので注意。

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7