使用JavaScript设置div的高度和宽度?

时间:2012-11-06 01:06:11

标签: javascript jquery html css

我试图通过javascript设置div的高度和宽度,但无济于事。我尝试了很多东西,到目前为止没有运气,请告诉我哪里出错了?我认为这只是直截了当的......

我不确定这里的问题是什么,我不能在这种情况下使用CSS来设置我需要在JavaScript中完成的变量,这是另一个主题。

<div id="demo">Demo Div</div>

<script>
    var test = document.getElementById("demo");
    test.style.width = "100px";
    test.style.height = "100px";
    test.style.cssText = 'border:1px solid black;'
</script>

提前谢谢。(我也对jQuery替代方案持开放态度)

-Epik -

2 个答案:

答案 0 :(得分:6)

问题是你的最后一行是设置cssText,它会覆盖前两行设置的样式而不是添加它们。试试这个:

var test = document.getElementById("demo");
test.style.width = "100px";
test.style.height = "100px";
test.style.border = '1px solid black'

演示:http://jsfiddle.net/ZtyfB/

既然你提到了jQuery,这里有一种方法你可以用它来做同样的事情:

$("#demo").css({
    width : "100px",
    height : "100px",
    border : '1px solid black'
});

答案 1 :(得分:0)

cssText会覆盖您设置的高度和宽度,以及您拥有的任何其他样式。

JQuery,感谢nnnnnn

$("#demo").css({
    width : "100px",
    height : "100px",
    border : '1px solid black'
});

我建议像cssText一样删除border,如下所示:

var test = document.getElementById("demo");
test.style.border = '1px solid black';
test.style.width = "100px";
test.style.height = "100px";

但是如果你真的需要cssText,那么先使用它:

var test = document.getElementById("demo");
test.style.cssText = 'border:1px solid black;';
test.style.width = "100px";
test.style.height = "100px";

最后一个可行的解决方案是使用cssText完成所有操作:

var test = document.getElementById("demo");
test.style.cssText = 'border:1px solid black; width: 100px; height: 100px';