开发者

Own function with multiple "if" conditions in jquery

开发者 https://www.devze.com 2023-01-17 03:35 出处:网络
Actually I whant to feed a variable \"var xy\" with diverent heights in dependence of more than one \"if\" condition. The best way to do this, is to create a custom function,isn\'t it?

Actually I whant to feed a variable "var xy" with diverent heights in dependence of more than one "if" condition. The best way to do this, is to create a custom function,isn't it? Well, I don't know how to do that. I've done something like this to get the height of diverent elements in dependence of the "item_xy" hasClass "current":

$.fn.varheight = function() {
   if ($("item_1").hasClass("current")) { ($("#container_1").height();}
   if ($("item_2").hasClass("current")) { ($("#container_2").height();}
   if ($("item_3").hasClass("current")) { ($("#container_3").height();}
   if ($("item_4").hasClass("current")) { ($("#container_4").height();}
});

Think of a menu. If the first menuitem hasClass "current" get the h开发者_JS百科eight of one element, if the second menuitem hasClass "current" in stad of the first, get the height of another element ... an so on.. The elements to get the heigt from are not the menu or menuitems. These are just some divs with content and diverent selectors like "#container_1", "#container_2",....

After that I want to use the .varheight() as setter.

Please give me a hint.


Sounds like what you want to do is set the height of multiple elements to be the same as the largest one. Correct? If so, this should work:

// Get the largest height
var height = 0;
$('.current').each(function(i,e) {
   if ($(e).height() > height
      height = $(e).height();
});

// Set the height of all to new value
$('.current').height(height);

There may be more concise ways to do this, but I wanted to present this in a way that is easier to understand.

If you really want this to be an extension to jQuery

// make sure the $ is pointing to JQuery and not some other library
(function($){
    // add a new method to JQuery

    $.fn.equalHeight = function() {
       // find the tallest height in the collection
       // that was passed in (.column)
        tallest = 0;
        this.each(function(){
            thisHeight = $(this).height();
            if( thisHeight > tallest)
                tallest = thisHeight;
        });

        // set each items height to use the tallest value found
        this.each(function(){
            $(this).height(tallest);
        });
    }
})(jQuery);

found here: http://brenelz.com/blog/jquery-custom-plug-in-equal-height-columns/

0

精彩评论

暂无评论...
验证码 换一张
取 消