Find distance between two DIVs using jQuery?

后端 未结 3 1008
灰色年华
灰色年华 2020-12-30 20:43

I have two DIVs that I need to know the calculated browser distance (in height) of them. I have read about the offset feature but the examples were not written for the way I

相关标签:
3条回答
  • 2020-12-30 21:24

    Use .offset():

    $('.foo').offset().top - $('.bar').offset().top
    
    0 讨论(0)
  • 2020-12-30 21:36

    This function finds the distance in pixels between the centre of two elements, no jquery:

    function distanceBetweenElems(elem1, elem2) {
        var e1Rect = elem1.getBoundingClientRect();
        var e2Rect = elem2.getBoundingClientRect();
        var dx = (e1Rect.left+(e1Rect.right-e1Rect.left)/2) - (e2Rect.left+(e2Rect.right-e2Rect.left)/2);
        var dy = (e1Rect.top+(e1Rect.bottom-e1Rect.top)/2) - (e2Rect.top+(e2Rect.bottom-e2Rect.top)/2);
        var dist = Math.sqrt(dx * dx + dy * dy);
        return dist;
    }
    

    I use it like this:

    var target1 = document.querySelector('#foo');
    var target2 = document.querySelector('#bar');
    if (distanceBetweenElems(target1,target2)<100){
         target1.classList.add('active');
    }
    
    0 讨论(0)
  • 2020-12-30 21:37

    Something like this should work:

    $('.foo').offset().top - $('.bar').offset().top
    

    As long as each class only has one element on the page.
    If they are not unique, give the two elements an ID and reference with that.

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