0

Why in this code the text box that is created when I press push is not exactly the same as the one already displayed?

<html>  
<body id="bd">  
<input type="text" style="width: 30px; padding: 2px; border: 1px solid black"/>  
<input type="submit" value="Push" onclick="test()"/>   
<script type="text/javascript">   
function test() {   
    var txt = document.createElement('input');  
    txt.type = 'text';   
    txt.style = "width: 30px; padding: 2px; border: 1px solid black";   
    document.getElementById('bd').appendChild(txt);  
}  
</script>  
</body>  
</html>   

Update:
What I see in the fiddle of @Bergi:

enter image description here

4

3 回答 3

6

style属性不是字符串。它是一个对象,其中每个 CSS 属性都表示为一个 DOM 属性。

它还具有包含所有规则cssText属性。

txt.style.cssText = "width: 30px; padding: 2px; border: 1px solid black";
于 2013-06-03T20:09:35.637 回答
1

对于您以编程方式创建的文本框,您正在设置txt.type = 'input';,但在您设置的原始文本框中type="text"。更改txt.type = 'input';txt.type = 'text';

如果要style在一个字符串中设置,请使用txt.style.cssText =.

于 2013-06-03T20:12:08.920 回答
1
 txt.style.width ="30px";
 txt.style.padding ="2px";
 tet.style.border ="1px"; 

通过 className 属性动态操作类确实是最佳实践,因为所有样式挂钩的最终外观都可以在单个样式表中控制。一个人的 JavaScript 代码也变得更简洁,因为不再专注于样式细节 (MDN)

cssText 返回样式规则的实际文本。能够动态设置样式表规则

 txt.cssText = style here;
于 2013-06-03T20:12:28.903 回答