代码之家  ›  专栏  ›  技术社区  ›  Nathan Osman

为什么这个分区不在正确的位置?

  •  1
  • Nathan Osman  · 技术社区  · 14 年前

    好吧,问题出在这里。我有一张单子,上面有一大堆东西。对于每个项目,都有一个相应的DIV,当项目悬停在上面时,该DIV将下拉。

    样品可以找到 here .

    现在,除非向下滚动一点,否则它可以正常工作。 然后 尝试将鼠标悬停在项目上。然后它在页面上滑得比预期的更远。

    以下是上面链接的页面中的相关代码:

    <script type="text/javascript">
    
    function doOver(num)
    {
        $('#s' + num).position({ of: $('#m' + num),
                                 my: 'left top',
                                 at: 'left bottom' });
        $('#s' + num).slideDown();
    }
    
    </script>
    
    ...
    
    <ul id="test" style="width: 400px; height: 25px; background-color: red;">
      <li id='m1' onmouseover='doOver(1)'>TestItem1</li>
      <li id='m2' onmouseover='doOver(2)'>TestItem2</li>
      <li id='m3' onmouseover='doOver(3)'>TestItem3</li>
    </ul>
    
    <div id='s1' style='width: 100px; height: 50px; position: absolute;'></div>
    <div id='s2' style='width: 100px; height: 50px; position: absolute;'></div>
    <div id='s3' style='width: 100px; height: 50px; position: absolute;'></div>
    
    ...
    

    知道为什么会这样吗?

    2 回复  |  直到 14 年前
        1
  •  1
  •   Gabriele Petrioli    14 年前

    问题似乎出在 position 用户界面的方法。 下面的工作似乎很好

    function doOver(num)
    {
        var $m = $('#m'+num);
        var mPos = $m.position();  // you could you $m.offset() here (depenging on the overall structure)
        var mHeight = $m.outerHeight();
        $('#s' + num).css({ 'top':mPos.top + mHeight, 'left':mPos.left });
        $('#s' + num).slideDown();
    }
    

    演示: http://www.jsfiddle.net/jnUsN/1/

        2
  •  0
  •   Nathan Osman    14 年前

    嗯,我发现了一些有用的东西:

    [view modified sample]

    相关代码:

    function Position(item,parent)
    {
        $(item).position({ of: $(parent), my: 'left top', at: 'left bottom' });
    }
    
    function doOver(num)
    {
        $('#s' + num).css('height','0px');
        $('#s' + num).show();
        Position('#s' + num,'#m' + num);
        $('#s' + num).hide();
        $('#s' + num).css('height','50px');
        $('#s' + num).slideDown();
    }
    

    …而且因为Chrome在第一次尝试时无法正确呈现:

    $(function() {
        Position('#s1','#m1');
        Position('#s2','#m2');
        Position('#s3','#m3');
    });