如何获得我的ul元素的高度?在没有jQuery的AngularJS中

How to get height of my ul element? In AngularJS without jQuery

本文关键字:jQuery AngularJS 高度 我的 何获得 ul 元素      更新时间:2023-09-26

Plnkr http://plnkr.co/edit/a7oV4gWzJG532RSqqOt3?p=preview

我正在一个Angular项目中构建自己的无限滚动能力,我需要获得我的ul的高度。

目前我正在使用这个:

标记
<ul id="tags-list">
  <li ng-repeat="t in tags">
    <div class="tag"
      ng-mouseover="showTagDetails(t)"
      ng-mouseleave="leaveTag(t)"
      ng-click="sendTag(t)">{{t.name}}</div>
    <tag-details tag="t"></tag-details>
  </li>
</ul>
控制器

if ($scope.tags.length != 0 || $scope.tags.length != undefined) {
    var theHeight = document.getElementById('tags-list').offsetHeight;
    // var h = theHeight.style.height;
    console.log(theHeight);
}

由于某种原因,.offsetHeight为我的ul返回0

var h = theHeight.style.height;没有返回任何东西。

我不想使用jQuery在这里获得高度,你会怎么做呢?

用$timeout把代码包装在if语句中,让Angular有足够的时间来改变DOM:

$timeout(function(){
  var theHeight = document.getElementById('tags-list').offsetHeight;
  console.log(theHeight);
});

我能够显示实际计算高度的唯一方法是等待Angular通过强制超时重新渲染DOM。

if ($scope.tags.length != 0 || $scope.tags.length != undefined) {
    var list= document.getElementById('tags-list');
    setTimeout(function(){
        console.log( list.offsetHeight );
    }, 100);
}

trevor的答案更好,因为它是一个angular超时服务。

工作活塞:http://plnkr.co/edit/RH1IBRVoowWFUoWvHGY8?p=preview

将代码包装在$timeout调用周围。当你的控制器初始化时DOM还没有被更新,这就是为什么你需要用$timeout来包装它。

$timeout(function() {
  if ($scope.tags.length != 0 || $scope.tags.length != undefined) {
    var theHeight = document.getElementById('tags-list').offsetHeight;
    // var h = theHeight.style.height;
    console.log(theHeight);
  }
});