简体   繁体   English

计算角度div1和div2之间的距离

[英]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. 尝试获取2格之间的距离。 I do it with this code, but my page automatically refreshes and the second div is zero. 我使用此代码执行此操作,但是我的页面自动刷新并且第二个div为零。 There is another method to calculate the distance ?. 还有另一种计算距离α的方法。

在此处输入图片说明

I did this in jquery. 我在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. 为此,我使用window.height,并删除了页眉和页脚元素的高度。 Then i bind a listener to a resize event of the object window to recomptue the height whenever it's needed. 然后,我将侦听器绑定到对象窗口的resize事件,以在需要时重新计算高度。

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. 如果要使其通用,则意味着要获取父组件的高度并减去第一个和最后一个,然后在父元素的整个高度上添加一个$ watch。

However height and width properties in javascript (and even jquery) are tricky. 但是,javascript(甚至jquery)中的height和width属性很棘手。 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. 然后,您可以通过查找height元素来获取标题的高度。

This has not really anything to do with angular, the only thing is the $watch part to detect changes. 这与angular并没有任何关系,唯一的是$ watch部分来检测更改。 But if it's for header/footer like me, you can just use raw javascript to listen for window resize. 但如果是像我这样的页眉/页脚,则可以使用原始javascript监听窗口调整大小。

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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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