Finding the position of bottom of a div with jquery

前端 未结 8 637
粉色の甜心
粉色の甜心 2020-12-07 18:29

I have a div and want to find the bottom position. I can find the top position of the Div like this, but how do I find the bottom position?

var top = $(\'#bo         


        
相关标签:
8条回答
  • 2020-12-07 18:45

    The answers so far will work.. if you only want to use the height without padding, borders, etc.

    If you would like to account for padding, borders, and margin, you should use .outerHeight.

    var bottom = $('#bottom').position().top + $('#bottom').outerHeight(true);
    
    0 讨论(0)
  • 2020-12-07 18:49

    Add the outerheight to the top and you have the bottom, relative to the parent element:

    var $el = $('#bottom');  //record the elem so you don't crawl the DOM everytime  
    var bottom = $el.position().top + $el.outerHeight(true); // passing "true" will also include the top and bottom margin
    

    With absolutely positioned elements or when positioning relative to the document, you will need to instead evaluate using offset:

    var bottom = $el.offset().top + $el.outerHeight(true);
    

    As pointed out by trnelson this does not work 100% of the time. To use this method for positioned elements, you also must account for offset. For an example see the following code.

    var bottom = $el.position().top + $el.offset().top + $el.outerHeight(true);
    
    0 讨论(0)
  • 2020-12-07 18:55

    EDIT: this solution is now in the original answer too.

    The accepted answer is not quite correct. You should not be using the position() function since it is relative to the parent. If you are doing global positioning(in most cases?) you should only add the offset top with the outerheight like so:

    var actualBottom = $(selector).offset().top + $(selector).outerHeight(true);
    

    The docs http://api.jquery.com/offset/

    0 讨论(0)
  • 2020-12-07 18:55

    The bottom is the top + the outerHeight, not the height, as it wouldn't include the margin or padding.

    var $bot,
        top,
        bottom;
    $bot = $('#bottom');
    top = $bot.position().top;
    bottom = top + $bot.outerHeight(true); //true is necessary to include the margins
    
    0 讨论(0)
  • var bottom = $('#bottom').position().top + $('#bottom').height();
    
    0 讨论(0)
  • 2020-12-07 18:59
    var top = ($('#bottom').position().top) + ($('#bottom').height());
    
    0 讨论(0)
提交回复
热议问题