我正在尝试通过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,但是标签却没有。
通过JavaScript使用class属性动态分配样式时是否有限制?

最佳答案

您应该使用className而不是class

lbl.className = 'label';


现代浏览器支持classList

lbl.classList.add("label");

09-17 01:13