insertRuleの使い方

はてなブログの方に「insertRuleの実験」というページを作りました。
うまく動いたのでご報告です。google chrome , firefox, ieで確認しました。


http://niming538.hatenablog.com/entry/2014/04/13/205250


css3のanimation , @keyframesを使うのに、cssを使わないで、javascriptで対応しようとして、jQueryでなにか便利な命令がないかと探したところ、なかったので、javascritのinsertRuleでできないかと試行錯誤しました。


若干読みにくいですが、javascriptスタイルシートを作って、insertRuleでスタイルシートにstyleを追加しています。今回、@keyframesがchromeが未対応なのでwebkit-keyframeとして、javascriptの条件分岐(if、else)を使っています。もっとスマートなやり方があるかもしれません。


いずれにしても、これでスタイルシートを書かないですべてjavascriptで対応できることになった気がします。
javascriptエライ!

<div id="sample01">Box</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">// <![CDATA[
$("div#sample01").css("width", "100px").css("background-color",
				"orange").css("height", "100px").css("padding", "10px").css(
				"margin", "30px").css("border", "2px solid orangered").css(
				"animation", "animationTest 5s ease 1s infinite normal");
		var sheet = (function() {
			var style = document.createElement("style");
			document.getElementsByTagName("head")[0].appendChild(style);
			return style.sheet;
		})();
		sheet.insertRule("#sample01 {text-align: center;}",0);
		var userAgent = window.navigator.userAgent.toLowerCase();
		if (userAgent.indexOf('chrome') != -1) {
			sheet.insertRule("@-webkit-keyframes animationTest { 0% { width: 50px; background: orange; } 50% { width: 100px; background: blue; } 100% { width: 150px; background: yellow; } }",0);
			} else  {
				sheet.insertRule("@keyframes animationTest { 0% { width: 50px; background: orange; } 50% { width: 100px; background: blue; } 100% { width: 150px; background: yellow; } }",0);
			};
// ]]></script>