我正在尝试创建一个jQuery函数,使所有元素都具有相同的高度。
我想这样称呼它
$('ul#items li').MakeSameHeight();
这应该使所有李的高度相同。所以我需要遍历所有的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));
答案 0 :(得分: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'});
答案 1 :(得分:0)
(document).ready(function(){
$.each($('ul#items li'), function() {
// or: $('ul#items li').each(function() {
$(this).css('height','someHeight');
});
});