如何通过JavaScript在属性之前应用css?

时间:2017-09-27 05:44:50

标签: javascript css selector

`   input.star:checked ~ label.star:before {
            content: '\f005';
            color: #FD4;
            transition: all .25s;
        }    `

如何通过javascript应用此代码?

1 个答案:

答案 0 :(得分:2)

如果你想用js添加一个样式,你可以使用style.sheet的insertRule(),示例代码:

var sheet = (function() {
	// Create the <style> tag
	var style = document.createElement("style");

	// WebKit hack :(
	style.appendChild(document.createTextNode(""));

	// Add the <style> element to the page
	document.head.appendChild(style);

	return style.sheet;
})();

// for a test
sheet.insertRule("body { background-color:red;}", sheet.length);

// for your code just replace param
// sheet.insertRule("input.star:checked ~ label.star:before {content: '\f005';color: #FD4;transition: all .25s;}}", sheet.length);