简体   繁体   中英

Using JavaScript to set the height and width of a div?

I am trying to set the height and width of a div through javascript and to no avail. I have tried numerous things and had no luck so far please advise me where i am going wrong? I thought this would just be straight forward...

I am not sure what the problem is here, I cannot use CSS in this case to set the variables i need to do it in JavaScript that is another topic all together though.

<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>

Thank you in advance.(I am open to a jQuery alternative as well)

-Epik-

The problem is that your last line is setting cssText , which overwrites the styles set on the first two lines rather than adding to them. Try this instead:

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

Demo: http://jsfiddle.net/ZtyfB/

And since you mentioned jQuery, here's one way you could use it to do the same thing:

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

The cssText is overwriting the height and width you set, as well as any other styling you had.

JQuery , thanks to nnnnnn :

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

I would recommend trashing cssText for border like so:

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

But if you really need cssText , then use it first:

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

The last viable solution is to do it all using cssText :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM