我正在使用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宽度来使其正确显示之外,还有其他诀窍可以延迟渲染后实现。