[英]Using Javascript or HTML, how to get the height and width of a div or other element?
[英]Calculating html element (div) width with javascript/dojo?
通常,当您在 html 中创建了一个 div 时。您可以使用 offsetWidth 或 style.width(如果已声明)检查其宽度。 但是,如果更改 innerHTML 使得 div 的宽度也发生变化,则这些函数都不起作用(不确定,但在我的情况下它们没有)。
一些代码:
var div = document.createElement("div");
div.innerHtml = "asdfasdfasdfasdfsdfasdfasdfad";
alert(div.style.width); // this is nothing
alert(div.offsetWidth); // this is 0
上面div的宽度是怎么得到的呢?
我意识到这是一个老问题,但对于许多从谷歌登陆这里的人,我会提供它。
这是 dojo 1.7+ 中的方法。 使用几何模块,您可以获取和设置内容的宽度(不包括填充或边框)。 这忽略了盒子大小。
require(['dojo/dom-geometry'], function(domGeom) {
var myDivNode = dojo.query('div')[0];
var contentBox = domGeom.getContentBox(myDivNode);
alert(contentBox.w);
// This is how to set width/height
domGeom.setContentSize(myDivNode, {w: 100, h: 100});
});
资料来源: https://dojotoolkit.org/reference-guide/1.7/dojo/contentBox.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.