可能重复:
如何创建<样式>带有Javascript 的标签
我使用java脚本编写了一个动态表单。我想在java脚本本身中添加样式。我写了一些代码来添加样式。但它不起作用。这是我在项目中编写的代码。
var sheet = document.createElement('style');
sheet.type="text/css";
sheet.innerHTML = "body{color:red;}";
document.body.appendChild(sheet);
请任何人帮帮我。
您的代码很好。但我认为你没有在正确的时间调用它,所以当你的身体标签加载时调用它
window.addEventListener('DOMContentLoaded',function(){
var sheet = document.createElement('style');
sheet.type="text/css";
sheet.innerHTML = "body{color:red;}";
document.body.appendChild(sheet);
}, false);
在这里你可以获得更多的资源来增加你的知识。我相信一个例子会非常有用!有一些这样的问题也会对你有所帮助 --署名Peter Boughton
这在IE、FF和Opera:中进行了测试
var css = 'h1 { background: red; }',
head = document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if(style.styleSheet){
style.styleSheet.cssText = css;
}else{
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
向元素添加类:
document.getElementById("MyElement").className += " MyClass";
从元素中删除类:
document.getElementById("MyElement").className =
document.getElementById("MyElement").className.replace
( /(?:^|s)MyClass(?!S)/ , '' )
/* code wrapped for readability - above is all one statement */
要在onclick事件中做到这一点:
<script type="text/javascript">
function changeClass()
{
// code examples from above
}
</script>
...
<button onclick="changeClass()">My Button</button>
更好的是,使用一个框架(在本例中为jQuery),它允许您执行以下操作:
$j('#MyElement').addClass('MyClass');
$j('#MyElement').removeClass('MyClass');
$j('#MyElement').toggleClass('MyClass');
还有:
<script type="text/javascript">
function changeClass()
{
// code examples from above
}
$j(':button:contains(My Button)').click(changeClass);
</script>
...
<button>My Button</button>
这将HTML标记与JS交互逻辑分离开来,这一点——尤其是在大型/复杂的应用程序上——可以使维护变得更加容易。
为什么不通过类添加样式?
.blue {
background-color: blue;
}
document.body.className = 'blue';
http://jsfiddle.net/kf8Nd/
如果您真的需要一个完整的样式表,只需将其添加到您的头中即可。
var sheet = document.createElement('style');
sheet.type="text/css";
sheet.innerHTML = "body{color:red;}";
document.head.appendChild(sheet); // head, not body
将样式添加到头部元素而不是主体
var sheet = document.createElement('style');
sheet.type="text/css";
sheet.innerHTML = "body{color:red;}";
document.head.appendChild(sheet);
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = 'body{color:red;}';
document.getElementsByTagName('head')[0].appendChild(style);