简体   繁体   中英

Calculate distance between div1 and div2 in angular

I used this code.

Math.abs($('.hd-termometro').offset().top - $('.ft-termometro').offset().top);

to try to get the distance between 2 divs. I do it with this code, but my page automatically refreshes and the second div is zero. There is another method to calculate the distance ?.

在此处输入图片说明

I did this in jquery. perhaps angular another method exists.

Usually i do this in order to resize the middle to push the footer at the bottom of my page.

For this i take the window.height and i remove the height of my header and footer element. Then i bind a listener to a resize event of the object window to recomptue the height whenever it's needed.

If we want to make it general this would mean to take the height of the parent component and substract the 1st and the last and add a $watch on the whole height of the parent element.

However height and width properties in javascript (and even jquery) are tricky. They don't compute the whole height taken by the element. Margins and border are excluded.

So in orde to get the right thing you have to wrapped your element with an inner padding

<section id="header">
    <div id="header-content">[content]</div>
</section>

With header having a padding property on it (if you need) and header-content having the border (if you need it). Then you can get the height of your header by looking for height element.

This has not really anything to do with angular, the only thing is the $watch part to detect changes. But if it's for header/footer like me, you can just use raw javascript to listen for window resize.

Do it in a function so that you can reuse it

function getDistance() { 
    var div1 = $('.hd-termometro');
    var div2 = $('.ft-termometro');
    return div2.offset().top - (div1.offset().top + div1.height())
}

Using it for the first time

$scope.distance = getDistance();

Update scope when distance changes

$(window).resize(function(){
   $scope.distance = getDistance();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM