等高元素

戴维·戴维斯(David J.Davis)

因此,我正在尝试使特定类别的对象完全相等,但要使其有用且过于简单,以便在各种文档中重新使用。

一切对我来说看起来都是合法合法的,但是有些事情搞砸了。

function cardHeights(divGroup) {
console.log("This is running");
divGroup.each(function (e) {
    var current = $(this),
        curTallest = 0;

    if (current.height() > curTallest) {
        curTallest = current.height();
        console.log(curTallest);
    }

    divGroup.height(curTallest);
});
}

然后,我使用它来调用该函数以使其工作。

$(document).ready(function () {
    cardHeights('.card');
    $(window).on('resize', cardHeights('.card')); 
});

这是我可以使用的Codepen,但是我无法在实际站点上使用它。这对我来说很奇怪。它给出一个错误,它不是一个已定义的函数。

TypeError:e.each不是一个函数

http://codepen.io/ddavisgraphics/pen/ZYQxqq

showdev

要重申我的意见:

  1. curTallest每次迭代重置将阻止找到最高的元素。循环中的每个元素都将被视为最高元素,因为每次都将其curTallest重置为零。

  2. 您只需要重置divGroupif的高度current.height() > currTallest当前,无论是否currTallest更改,您都将在每次迭代时重置高度

  3. cardHeights()需要一个jQuery对象。您正在传递一个字符串。传递jQuery对象或将字符串转换为函数内的对象。


话虽如此,我的建议是收集所有高度,从这些值确定最大高度,并将所有高度设置为最大高度。这样可以防止多次不必要地设置高度。

这是一个例子:

$(function() {
  cardHeights('.card');
  $(window).on('resize', cardHeights('.card'));
});


function cardHeights(divGroup) {

  /* Initialize variables */
  var heights = [],
      $group = $(divGroup);

  /* Iterate through the selected elements, pushing their heights into an array */
  $group.each(function() {
    heights.push($(this).height());
  });

  /* Determine the maximum height in the array */
  var maxHeight = Math.max.apply(Math, heights);

  /* Set the height of all elements in the group to the maximum height */
  $group.height(maxHeight);

}
div.card {
  background-color: #CCC;
  margin: 1em;
  padding: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="card">Test</div>
<div class="card">Test<br />Tester<br />Testing<br />Test-o-rama<br />Tallest!</div>
<div class="card">Test<br />Tester</div>

编辑

如果由于某种原因,您不想使用数组,则可以使用将每个元素的高度与最大高度进行比较的原始方法:

function cardHeights(divGroup) {

  /* Initialize variables */
  var $group = $(divGroup),
      maxHeight=0,
      thisHeight=0;

  /* Iterate selected elements, reset maxHeight if the current height is taller */
  $group.each(function() {
    thisHeight=$(this).height();
    if (thisHeight>maxHeight) {maxHeight=thisHeight;}
  });

  /* Set the height of all elements in the group to the maximum height */
  $group.height(maxHeight);

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章