【发布时间】:2010-10-15 16:35:13
【问题描述】:
我正在使用 jQuery 在一个函数中执行以下操作:
最初我有一个绝对定位的 DIV; 我将 DIV 的内部 HTML 设置为一些需要的文本/HTML; 然后我使用 css({top: initialTop,left: initialLeft}) 在某些特定坐标处显示元素。
在页面的左侧和中心区域内一切正常 - 我在请求的坐标处看到左上角的 DIV。
当我想在页面右侧显示元素时,我必须保持 DIV 100% 可见,因此我必须在请求的坐标处显示其右上角(而不是左上角)。 我可以毫无问题地获得窗口宽度和滚动偏移量,并且可以计算从 DIV 的左上角减去的偏移量以使其成为右上角 - 我只取 DIV 的宽度并从坐标中减去它。
问题是 - 这种方法仅在我更改 DIV 的内容后第二次才有效。我第一次调用 myDiv.width() 时,它会保留以前的值 - 带有旧文本的 DIV 的宽度。我第二次为同一个元素调用同一个函数时,一切正常。
我听说过一些关于延迟渲染的事情——这似乎发生在我的案例中;在函数退出之前,浏览器不会使用更新的文本呈现 DIV,因此我无法获得正确的宽度。
下面是简化代码:
// at the beginning I have the following style:
#myDiv
{
position: absolute;
top: 0;
left: 0;
}
function PutDivWithInPlace(text, x) {
var $div = $('#myDiv');
$div.html(text);
$div.show(); // even if it worked, I would really like to keep myDiv invisible to avoid it jumping from the old position to the new one
var width = $div.outerWidth();
// I ignore x-scroll offset here for simplicity
// if the right edge of div flows over the window right side, then push it to the left
if (x + width > $(window).width()) {
x -= width;
}
$div.css({
left: x
});
// this does not work - the width is still from the previous call of PutDivWithInPlace, so myDiv appears at the wrong place :(
}
是否有任何其他方法可以获取 DIV 的右上角,我需要它位于我更改 DIV 内容的相同功能中(但前提是 DIV 确实溢出窗口右侧)?除了使用 DIV 的宽度,即使在延迟渲染之后,也许还有其他一些技巧?
【问题讨论】:
-
你能把你的代码贴在这里吗??以便我们对其进行审核。
-
确实,我们需要查看您正在使用的代码。