繁体   English   中英

JavaScript:如何获得动态创建的元素的宽度?

[英]JavaScript: How to get a dynamically created element's width?

我是一个JavaScript新手。 对我有耐心。

我搜索了这个网站的相关问题,发现了两个: 如何在AngularjjQuery + CSS中 使用$ comiple获取动态创建元素的宽度 如何计算innerHTML的高度和宽度? 它们的相关性和答案将在下面讨论。 如果我错过了相关问题并且这是一个重复的问题,请指导我。

我动态创建一个<div class="popup"> (称之为“popup”),用innerHTMLdisplay: none;填充它display: none; 标记中的<div> ,并将其插入页面。 相关的CSS是:

.popup {
   top: 0;
   left: 0;
   width: 200px;
   height: 250px;
 }  

使用event.clientX ,我在mouseover事件触发时相对于光标位置定位弹出,如下所示:

var widthOffset = 75, heightOffset = 0;
var windowWidth, popupWidth;
// other code ...
windowWidth = $(window).width();
popupWidth = 200;   // popup.style.width returns nothing (not null,
                    // not undefined, just nothing).
// when event.clientX is in the left half of the window, display popup
// offset to the right of clientX;
// when clientX is in the right half, display popup offset to the left.
if( event.clientX > windowWidth/2 ){ widthOffset = -(widthOffset + popupWidth);}
popup.style.top = event.clientY - heightOffset + "px";
popup.style.left = event.clientX + widthOffset + "px";

CodePen上的Pen Popup Project简化案例中有一个减少工作的案例

问题是我想以编程方式获取popupWidth而不是将其设置为固定数量。 但是,正如评论所述,

popupWidth = popup.style.width;  

没什么。 (也许它是一个空字符串:popupWidth ===“”。我不确定。)

上面提到的第一个问题的答案是尝试获取宽度之前将弹出窗口插入DOM。 我做到了这一点。 (参见笔。)但是,它不起作用。

对第二个问题的第二个答案的评论说:

根本问题是无法使用display:none在元素上设置高度。

我有display: none ,但当我将其更改为display: block ,并设置popupWidth = popup.style.width; ,弹出窗口“猛吃”鼠标悬停。

所以问题仍然存在:我如何以编程方式获取popupWidth ,就像我使用windowWidth

在@Redu和@torazaburo的帮助下,答案变得清晰了。

popupWidth = popup.offsetWidth; 是正确的陈述,但这两个条件必须是真的:

  1. 弹出窗口必须已插入DOM中,并且
  2. display: block; 必须已经设定。

如果弹出窗口仍在内存中或display: block; 尚未设置,然后popup.offsetWidth === 0.如果两个条件都为真,则popup.offsetWidth等于CSS中设置的宽度。

感谢两位评论者的帮助。

你可以这样做

var popupDiv = document.getElementsByClassName("popup")[0],
       width = window.getComputedStyle(popupDiv).width;

如果处理元素的窗口或文档类型,则getElementsByClassName(element,null)element.offsetWidthelement.clientWidth不起作用。 您必须访问宽度值,如

var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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