在javascript中通过class属性应用样式时是否有限制?

Is there a limitation when applying the style via the class attribute in javascript?

本文关键字:样式 是否 有限制 应用 属性 javascript class      更新时间:2023-09-26

我试图通过javascript创建一个标签,但css似乎不适用。
示例代码(在Chrome中测试):

<html>  
<head>  
<style type="text/css">  
#wrapper {  
    width:700px;  
}  
#form_groups .label {  
    float:left;  
    clear:left;  
    width:180px;  
    margin-right:3px;  
    margin-top:2px;  
    background-color:red;  
}  
#the_id {  
    background-color: #FBEF99;  
    font-family:"Lucida Console", Monaco, monospace;  
    font-size: .9em;  
    width: 300px;  
    margin-top: 2px;  
}  
</style>  
</head>  
<body>  
<input type="submit" value="Create" onclick="createForm()"/>  
<div id="wrapper">  
<form id="form_groups" action="">  
    <label class="label">Id</label>  
    <input id="the_id" type="text" value="1">     
</form>  
</div>  
<script type="text/javascript">  
function createForm () {  
    var wrapper = document.getElementById('wrapper');  
    var form = document.getElementById('form_groups');  
    wrapper.removeChild(form);       
    form = document.createElement('form');  
    form.id='form_groups';  
    var lbl = document.createElement('label');  
    lbl.textContent = 'Name';  
    lbl.class = 'label';      
    var name = document.createElement('input');  
    name.type = 'text';  
    name.id='the_id';       
    form.appendChild(lbl);  
    form.appendChild(name);     
    wrapper.appendChild(form);  
}  
</script>  
</body>  
</html>

当我按下按钮Create时,文本得到css,但标签没有。
是否有一个限制时,分配一个样式使用class属性动态通过javascript?

您应该使用className而不是class

lbl.className = 'label'; 

现代浏览器支持classList

lbl.classList.add("label");