我想使用具有动态高度内容的tinker jquery插件。 我需要知道三个第一元素的总高度,我该如何计算?
<div class="myWrapper" ticker>
<div>
<div ng-repeat="latest in latests" class="latest">
<p ng-bind-html="latest.txt"></p>
</div>
</div>
</div>
我的指示:
restrict: 'A',
link: function($scope, element) {
var height = //I need the total height of the firsts three divs with class latest
element.easyTicker({
height: height',
interval: 5000
});
}
答案 0 :(得分:1)
由于您需要让角度渲染元素,我会将指令放在转发器上,然后您可以检查$last
子范围内的ng-repeat
属性。
<div class="myWrapper">
<div>
<div ng-repeat="latest in latests" class="latest" ticker-item>
<p ng-bind-html="latest.txt"></p>
</div>
</div>
</div>
指令
app.directive('ticker-item', function () {
restrict: 'A',
link: function ($scope, element) {
var height = 0;
/* wait for last element in ng-repeat */
if ($scope.$last) {
element.siblings(':lt(3)').each(function () {
height += $(this).height();
});
element.closest('.myWrapper').easyTicker({
height: height,
interval: 5000
});
}
}
});
如果插件未正确设置最后一个元素,请在指令中注入$timeout
并在$timeout()
中包装插件初始化。这将确保所有转发器元素都已首先呈现
答案 1 :(得分:0)
restrict: 'A',
link: function($scope, element) {
var height = function () {
ii = 0;
for (i = 0; i < 3; i++)
ii += document.getElementsByClassName('latest')[i].style.height;
return ii;
};
element.easyTicker({
height: height,
interval: 5000
});
}
答案 2 :(得分:0)
尝试这样的事情:
var el = $('.latest'), //your element
heights = 0; //counter to be stored
for(var i = 0; i < 3; i++){ // adjust the "less than" to show how much to count
heights += el.eq(i).height();
}
alert(heights);
&#13;
div { border: 1px solid red; }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="latest" style="height: 200px"></div>
<div class="latest" style="height: 150px"></div>
<div class="latest" style="height: 100px"></div>
&#13;
答案 3 :(得分:0)
我对Tinker一无所知,但我知道在vanilla jQuery中这很容易做到。例如:
<强> HTML 强>
<div id="example-wrapper">
<!-- here are the children we care about -->
</div>
Javascript / JQuery
function count(){
var height = 0;
var count = 0;
$("#example-wrapper").children().each(function(i){
if(count < 3){
height += $(this).height();
}
count += 1;
});
return count;
}
您可以使用jQuery each()
函数迭代元素的所有子元素。
答案 4 :(得分:0)
这是一个使用slice()的jQuery解决方案,它应该比以下方法更有效:lt(3)
function calcHeight(){
var height = 0;
$('.myWrapper .latest').slice(0, 2).each(function(){
height += $(this).height();
});
return height;
}