1

我正在尝试制作一个 jQuery 函数来使所有元素的高度相同。

我想这样称呼它

$('ul#items li').MakeSameHeight();

那应该使所有li的高度相同。所以我需要遍历所有的 li 并获得最大高度。我怎么做?例如。

(function ($) {
  $.fn.MakeSameHeight() = function (opts) {
    // What do I put here?
  };
} (jQuery));

编辑 :

如果有人好奇,这是我的最终功能,感谢 PSL

(function ($) {
  $.fn.MakeSameHeight = function (opts) {
    var maxH = 0;
    this.each(function () {
      maxH = Math.max(maxH, $(this).height());
    });
    this.each(function () {
      $(this).height(maxH);
    });
    return this;
  };
} (jQuery));
4

2 回答 2

1

这是你想要的:-

(function ($) {
  $.fn.MakeSameHeight = function (opts) {

//this inside the jquery plugin function refers to the result of jquery selector which          
 //itself is a jquery object. In this case it is list of li's
      this.each(function(){ //iterate through the selected elements
         alert($(this).css('height'));  //here do $(this) to get that particular element
         //to set the height $(this).css('height','yourheightvalue');
      });
    // What do I put here?

   return this;  //return the elements back for chaining.
  };
} (jQuery));

$('ul#items li').MakeSameHeight();

小提琴

例子:-

(function ($) {
  $.fn.MakeSameHeight = function (opts) {
      this.each(function(){
     $(this).css('height', opts.height);
      });
    return this;
  };
} (jQuery));

$('ul#items li').MakeSameHeight({'height':'30px'});
于 2013-05-15T03:11:54.493 回答
0
(document).ready(function(){ 
    $.each($('ul#items li'), function() {
// or: $('ul#items li').each(function() {
        $(this).css('height','someHeight');
    });
});
于 2013-05-15T03:13:16.903 回答