[英]Javascript width of div, returns 0
I m trying to retrieve the width of an div for my function with javascript:我正在尝试使用 javascript 为我的函数检索 div 的宽度:
#areaDraw {
margin-top:50px;
width: 50%;
min-height: 100%;
z-index: 1000;
}
and the function:和功能:
Event.add(window, "resize", function() {
sketch.resize(document.getElementById("areaDraw").style.width, window.innerHeight);
}).listener();
somehow javascript always returns 0 for the width of the div(areaDraw)不知何故,javascript 总是为 div(areaDraw) 的宽度返回 0
so whats wrong with:那么有什么问题:
document.getElementById("areaDraw").style.width
尝试document.getElementById("mydiv").offsetWidth
而不是.style.width
Use this instead:改用这个:
document.getElementById("areaDraw").offsetWidth
Edit: As requested, an explanation of why this works (just as an extra reference).编辑:根据要求,解释为什么会这样(作为额外的参考)。
It's because the property style.width
is the width as defined explicitly in the CSS, wheareas offsetWidth
finds the actual width of the element as it's displayed in the browser.这是因为属性
style.width
是 CSS 中明确定义的宽度, wheareas offsetWidth
查找元素在浏览器中显示时的实际宽度。
document.getElementById("areaDraw").offsetWidth
试试这个:)
Your #areaDraw
div
element is probably empty at the moment you try to get the width of it.在您尝试获取其宽度时,您的
#areaDraw
div
元素可能是空的。
element.style.width
gets the width of the content of the element, regardless the padding
or margin
attributes. element.style.width
获取元素内容的宽度,而不管padding
或margin
属性。
Try using the .offsetWidth
( Source: MDN ) attribute.尝试使用
.offsetWidth
(来源:MDN )属性。 The difference is that it includes the full width of the element with its padding
and margin
attributes.所不同的是,它包括与它的元件的全宽
padding
和margin
的属性。
See the MSDN example along with its reference .请参阅MSDN 示例及其参考。
You could also try using window.getComputedStyle
您也可以尝试使用
window.getComputedStyle
var elem = document.getElementById("areaDraw");
var width = window.getComputedStyle(elem, null).width;
Take into account that width will be a string in this case (e,g '290.5px')考虑到在这种情况下宽度将是一个字符串(例如'290.5px')
getComputedStyle() gives the final used values of all the CSS properties of an element.
getComputedStyle() 给出元素的所有 CSS 属性的最终使用值。
Element must have style="display: block;"元素必须有 style="display: block;" and My solution:
和我的解决方案:
intId = 0;
function resize(con)
{
var width = con.offsetWidth;
if (width == 0)
{
var resfnc = function(con)
{
return function()
{
var width = con.offsetWidth;
if (width == 0)
{
return;
}
clearInterval(intId);
resize(con);
}
}
intId = setInterval(resfnc(con), 50);
return;
}
//...... work here
}
var resf = function (con)
{
return function ()
{
resize(con);
};
};
var con = document.querySelector("#elementID");
window.addEventListener('resize', resf(con), true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.