我正在使用 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 宽度来确保在延迟渲染后正确显示外,还有其他一些技巧吗?
最佳答案
我不确定你到底在问什么,但是是不是不可能设置
left:auto;
right:someCoordinate;
我觉得无论宽度如何,都应该将它放在右侧。
关于jquery - 如何在浏览器窗口的右侧重新定位动态 HTML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3944244/