[英]Get DIV width and height in javascript
我正在嘗試獲取div寬度和高度,因為用戶更改它並將該數字提交到另一個頁面。 我似乎無法弄清楚如何獲得寬度和高度。
<script>
$(function() {
$( "#set div" ).draggable({
stack: "#set div",
preventCollision: true,
containment: $('#main_content'),
stop: function(event, ui) {
var mydiv = document.getElementById("set");
var pos_x = ui.offset.left;
var pos_y = ui.offset.top;
var width = mydiv.style.width; ----THIS DOESN'T WORK
var height = mydiv.style.height; ----THIS DOESN'T WORK
var window_width = window.innerWidth;
var window_height = window.innerHeight;
var need = ui.helper.data("need");
console.log(pos_x);
console.log(pos_y);
console.log(width);
console.log(window_width);
console.log(need);
//Do the ajax call to the server
$.ajax({
type: "POST",
url: "updatecoords.php",
data: { x: pos_x, y: pos_y, need_id: need, width: width, height: height, window_width: window_width, window_height: window_height}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
});
});
</script>
這樣做的正確方法是什么?
使用ele.style.width
來獲取元素的寬度是錯誤的!!!!!!
在本機JavaScript中,您可以通過兩種方式獲取元素的CSS:
window.getComputedStyle(ele)
例如,
var ele = document.getElementById("content"), // Do not use #
eleStyle = window.getComputedStyle(ele);
/* Below is the width of ele */
var eleWidth = eleStyle.width;
element.currentStyle
例如,
var ele = document.getElementById("content"), // Do not use #
eleStyle = ele.currentStyle;
/* Below is the width of ele */
var eleWidth = eleStyle.width;
ele.style
? ele.style
只是獲得ele
的歸屬風格。 如果你使用ele.style.width
,你只需要獲得ele.style
的寬度,而不是ele
的實際寬度。
如果你做了類似的事情:
ele.style.width = "55px"
使用ele.style.width
時會得到“55px”。 如果還沒有,你會得到不確定的。
使用$ele.width()
(如果你想要“精確”寬度,使用$ele.outWidth()
),jQuery已經為你做了一切。
在普通的JavaScript中使用
var width = mydiv.offsetWidth;
var height = mydiv.offsetHeight;
這將為您提供數值,或
var width = mydiv.offsetWidth + 'px';
var height = mydiv.offsetHeight + 'px';
如果你想要它們的“CSS”格式。
既然你已經在使用jQuery了,你可以這樣做:
var width;
if (need == 1) {
width = $("#web").width();
} else {
width = $("#set").width();
}
既然你正在使用jQuery,你可能想知道以下內容:
$('#id')。outerWidth()$('#id')。outerWidth(true)
這些將非常方便。 這允許您查找div的總寬度(填充,邊框,寬度和(可選參數)邊距)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.