jQuery dynamically change element height

前端 未结 4 2062
滥情空心
滥情空心 2021-01-04 20:01

I\'m working on a fluid layout project. I have some fixed height DIVs in my document, and the heights are different for all of them. I need to proportionally change these DI

4条回答
  •  迷失自我
    2021-01-04 20:26

    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);
      });
    });
    

提交回复
热议问题