jQuery动态更改元素高度

the*_*der 9 jquery height window-resize

我正在进行流体布局项目.我的文档中有一些固定高度的DIV,所有这些都有不同的高度.我需要在浏览器调整大小时按比例更改这些DIV的高度.这是标记.

<body>
<div id="a" class="target"></div>
<div id="b" class="target"></div>
<div id="c" class="target"></div>
</body> 
Run Code Online (Sandbox Code Playgroud)

和css:

<style>
    body { width: 90%; margin: 0 auto;} 
    .target { width:30%; float:left; margin:1.6%; cursor:pointer; }
    #a { height: 200px; background-color: yellow;}
    #b { height: 400px; background-color: green;}
    #c { height: 600px; background-color: grey;}
</style>
Run Code Online (Sandbox Code Playgroud)

听起来很简单!主要条件是我不知道预定量的目标DIV及其ID,这就是我使用.each(function())的原因.这是我写的脚本:

$(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*/
$(".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); 
});
Run Code Online (Sandbox Code Playgroud)

});

当用户重新加载页面时,此脚本完美有效.当用户在没有重新加载的情况下调整浏览器大小时,如何才能获得相同的结果?我知道我应该应用$(window).resize事件监听器.但问题是DIV的初始高度将在事件内部进行计算,结果将像无限循环一样 - 即最终高度将在巨大的进展中增加或减少.我不需要那个!如何在事件函数外部进行每个 DIV初始高度计算,然后在事件函数中使用这些高度?或者可能有另一种方法可以获得相同的结果?

Jua*_*des 14

您需要存储每个div的原始高度.有不同的方法,这里是一个hack,将它存储在DOM节点本身(有更好的方法,但这是快速和肮脏的).

$(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);
  });
});
Run Code Online (Sandbox Code Playgroud)