jQuery dynamically change element height

心不动则不痛 提交于 2019-11-30 18:48:55

You need to store the original height of each div. There are different ways to do it, here's one hack, store it in the DOM node itself (there are better ways, but this is quick and dirty).

$(document).ready(function(){
  //set the initial body width
  var originalWidth = 1000; 
  /*I need to go through all target divs because i don't know
  how many divs are here and what are their initial height*/


  function resize() {
    //This will only set this._originalHeight once
    this._originalHeight = this._originalHeight || $(this).height();
    //get the new body width
    var bodyWidth = $("body").width(); 
    //get the difference in width, needed for hight calculation 
    var widthDiff = bodyWidth - originalWidth; 
    //new hight based on initial div height
    var newHeight = this._originalHeight + (widthDiff / 10); 
    //sets the different height for every needed div
    $(this).css("height", newHeight); 

  }

  $(".target").each(resize);
  $(document).resize(function(){
      $(".target").each(resize);
  });
});

Wrap up your resize functionality and subscribe to the window resize event.

$(document).ready(function(){
   //set the initial body width
   var originalWidth = 1000; 
   resizeTargets();
   $(window).resize(resizeTargets);

});

function resizeTargets()
{
   $(".target").each(function() 
   {
       //get the initial height of every div
       var originalHeight = $(this).height(); 
       //get the new body width
       var bodyWidth = $("body").width(); 
       //get the difference in width, needed for hight calculation 
       var widthDiff = bodyWidth - originalWidth; 
       //new hight based on initial div height
       var newHeight = originalHeight + (widthDiff / 10); 
       //sets the different height for every needed div
       $(this).css("height", newHeight); 
   });
}

take a look at the resize event that you can bind with jquery

http://api.jquery.com/resize/

use .data to store the initial size of the div inside your $.each function

$(this).data('height', $(this).height());
$(this).data('width', $(this).width());

you can later retrieve the old sizes within the resize callback

var old_height = $(this).data('height');
var old_width = $(this).data('width');

Hope this helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!