How to position a div dynamically below another?

前端 未结 4 1005
暗喜
暗喜 2021-02-08 01:59

I\'m trying to use jQuery to detect the position of a div (#olddiv), so I can use that position to place another div (#newdiv) exactly below it. The ri

相关标签:
4条回答
  • 2021-02-08 02:36

    I've used that in a website I made, to display a div in a certain position, always relative to another div and always relative to the dimensions of the browser window (even when you stretch it manually).

    Here's the code:

    // function to place the div
    var newdiv = function () {
       var o = $('#olddiv').offset();
       var h = $('#olddiv').height();
       var w = $('#olddiv').width();
       $('#newdiv').css({'top': o.top,
                         'left': o.left,
                         'width': w,
                         'height': h       
       }).show();
    }
    
    // listen the window changes and correct the newdiv position
    $(window).resize(function(){ newdiv(); });
    
    // display the newdiv after DOM is loaded, or whenever you want
    newdiv();
    

    Note that you may need to add another vars to the css above, like margin, padding, etc, in order to get the right position, or even add manually values to top and left, in case the new div isn't exactly like the old one.

    0 讨论(0)
  • 2021-02-08 02:44

    I've used offset() to position elements dynamically. Try this:

    var offset = $('#olddiv').offset();
    var height = $('#olddiv').height();
    var width = $('#olddiv').width();
    var top = offset.top + height + "px";
    var right = offset.left + width + "px";
    
    $('#ID').css( {
        'position': 'absolute',
        'right': right,
        'top': top
    });
    

    also don't forget to bind this to the window.onresize event if you need it to scale when the user resizes the window.

    UPDATE: another thought - does this have to be positioned absolutely? Why not just insert the div after the other in the DOM?

    $('#olddiv').after($('#ID').html());
    

    then just make sure they are the same width.

    0 讨论(0)
  • 2021-02-08 02:47

    There is a pretty cool plugin getting developed by the jQuery UI team that helps with position.

    Lets you do something like this:

    $(".menu").position({ my: "left top", at: "left bottom", of: ".menubutton" });
    
    0 讨论(0)
  • 2021-02-08 02:49

    Looks like a typo, does fixing:

    'top', right
    'right', top
    

    help at all?

    The divs need to be positioned absolutely or relatively in order for this code to work as well.

    0 讨论(0)
提交回复
热议问题