[英]Using JavaScript to set the height and width of a div?
我試圖通過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替代品)
-史詩-
問題是您的最后一行設置的是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'
});
cssText
會覆蓋您設置的高度和寬度以及您擁有的任何其他樣式。
$("#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';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.