【发布时间】:2016-05-07 05:30:49
【问题描述】:
我是 JavaScript 新手。对我有耐心。
我在这个网站上搜索了相关问题,发现了两个:How to get width of a dynamically created element with $comiple in Angularj 和 jQuery + CSS. How do I compute height and width of innerHTML?。它们的相关性和它们的答案将在下面讨论。如果我错过了一个相关问题并且这是一个重复的问题,请指导我。
我动态地创建一个<div class="popup">(称为“弹出窗口”),用标记中的display: none;<div> 中的innerHTML 填充它,然后将其插入到页面上。相关的 CSS 是:
.popup {
top: 0;
left: 0;
width: 200px;
height: 250px;
}
使用event.clientX,我相对于鼠标悬停事件触发时的光标位置定位弹出窗口,如下所示:
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 Reduced Case 有一个有效的简化案例。
问题是我想以编程方式获取popupWidth,而不是将其设置为固定数量。但是,正如评论所述,
popupWidth = popup.style.width;
什么都不是。 (也许它是一个空字符串:popupWidth === ""。我不确定。)
上面提到的第一个问题的答案是在 尝试获取其宽度之前将弹出窗口插入 DOM。我已经做到了。 (见笔。)但是,它不起作用。
对第二个问题的第二个答案的评论说:
根本问题是无法在具有 display:none 的元素上设置高度。
我有display: none,但当我将其更改为display: block,并设置popupWidth = popup.style.width;,鼠标悬停时弹出“结结巴巴”。
所以问题仍然存在:我如何像使用 windowWidth 一样以编程方式获取 popupWidth?
【问题讨论】:
-
您没有使用 jQuery 函数是否有任何特殊原因,您似乎已将其包含在代码笔中?
-
嗯,是的。我不知道jQuery。研究“如何获得窗口宽度”这个问题让我得到了答案,JQuery 函数
$(window).width()。通过更多的研究,我学会了如何在 .js 文件中包含 JQuery。这就是我的 JQuery 知识的全部范围。能具体回答一下吗?
标签: javascript css dynamic