jQuery dynamically change element height

前端 未结 4 2060
滥情空心
滥情空心 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:05

    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); 
       });
    }
    
    0 讨论(0)
  • 2021-01-04 20:07

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

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

    0 讨论(0)
  • 2021-01-04 20:19

    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

    0 讨论(0)
  • 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);
      });
    });
    
    0 讨论(0)
提交回复
热议问题