2015-09-26 1 views
3

J'ai un problème avec jQuery. Je n'arrive pas à comprendre comment faire ça. J'ai plusieurs sections largeur différentes hauteurs:Redimensionner Hauteur des éléments lorsque la fenêtre Redimensionner

<section id="1" class="something" style="height:111px; background:red;">1</section> 
<section id="2" class="something" style="height:222px; background:blue;">2</section> 
<section id="3" class="something" style="height:333px; background:green;">3</section> 

Mon jQuery redimensionne l'hauteur de chaque section lorsque la fenêtre est plus petite que 500px:

var org_height = $('.something').height(); 

$(window).resize(function() { 

    $(".something").each(function() { 

     var win = $(window).width(); 
     var height = $('.something').height(); 

     if(win < 500) { 
      y = 500 - win; 
      $('.something').css("height",org_height-y/3+"px"); 
     } 
     else { 
      $('.something').css("height",org_height+"px"); 
     } 
    }); 

}); 

jsFiddle: https://jsfiddle.net/owtz31jj/

Comment puis-je stocker la hauteur d'origine de chaque section et les redimensionner en fonction de chaque hauteur et revenir à la hauteur d'origine à nouveau. J'apprécie grandement toute aide.

Répondre

2

Vous pouvez utiliser jQuey.fn.data:

// Store original height for each .something 
$(".something").each(function() { 
    $(this).data('org_height', $(this).height()); 
}); 
$(window).on('resize', function() { 
    var win = $(window).width(); 
    $(".something").each(function() { 
     // Get the value storred in org_height using jQuery.fn.data 
     var org_height = $(this).data('org_height'); 
     if(win < 500) { 
      var y = 500 - win; 
      $(this).css("height", org_height - y/3); 
     } 
     else { 
      $(this).css("height", org_height); 
     } 
    }); 
}); 
+0

C'était rapide. Merci beaucoup, ça fonctionne parfaitement. – user5379464

+0

Pas de problème. Vous voyez comment vous pouvez utiliser '$ (this)' dans chaque fonction? Cela s'assurera que vous obtenez l'org_height de l'élément correspondant. – andlrc

+0

Oui, j'aime jQuery de plus en plus;) – user5379464