代码之家  ›  专栏  ›  技术社区  ›  JustAMartin

如何在浏览器窗口的右侧重新定位动态HTML元素?

  •  3
  • JustAMartin  · 技术社区  · 15 年前

    我使用jQuery在一个函数中执行以下操作:

    我将DIV的内部HTML设置为一些所需的text/HTML;

    在页面的左边和中间区域,一切都很好-我看到了在要求的坐标左上角的DIV。

    当我想在页面的右侧显示元素时,必须使DIV 100%可见,所以必须在请求的坐标处显示它的右上角(而不是左上角)。 我可以得到窗口宽度和滚动偏移没有问题,我可以计算偏移量减去左上角的DIV,使其右上角-我只是采取DIVs宽度和减去它的坐标。

    我听说了一些关于延迟呈现的事情——在我的例子中似乎发生了;浏览器在函数退出之前不会用更新的文本呈现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确实溢出了窗口右侧)?也许除了使用DIVs width在延迟渲染之后也能得到正确的效果之外,还有其他一些技巧?

    2 回复  |  直到 12 年前
        1
  •  1
  •   dave    15 年前

    我不知道你到底在问什么,但是否不可能

    left:auto;
    right:someCoordinate;
    

    我觉得应该把它放在右边,不管它有多宽。

        2
  •  0
  •   JustAMartin    15 年前

    看来,我找到了一些奇怪的临时解决办法。 DIV宽度还取决于它在浏览器窗口中的显示位置。我不明白,为什么同一个DIV和同一个文本的宽度是200px,当它打开时,比如x=100,y=200,但是当我把它设为x=800,y=200时,它突然变为120px宽。浏览器似乎还考虑了元素的位置,虽然它允许窗口溢出,但仍然会自动缩小宽度。所以我的代码现在是这样的:

    function PutDivWithInPlace(text, x)
    {
    var $div = $('#myDiv');
    $div.html(text);
    
    var width = $div.outerWidth();
    
    // this is needed to recalc DIVs width because the browser has resized it depending on x
    $div.css({ left: x});
    
    // 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;
    }
    
    // and update css again with new style
    $div.css({ left: x});
    } 
    

    如果我调整浏览器窗口的大小,使坐标在边上,这对一个测试用例是有效的——我得到宽度,就像我把Div放在那些坐标上一样。 当然有一个问题-如果宽度很大,我把它推到左边,那么浏览器可能会决定再次调整DIV的大小,就像我在边上绘制之前那样。我希望这种情况不会经常发生。仍然没有更好的解决方案:(