如何通过jquery设置di​​v的高度等于下一个的高度?

时间:2015-11-15 12:03:56

标签: jquery

我的HTML代码是:

<div class="col-xs-4 white-bg v-text">
  <div class="">
    <h4>My header</h4>
  </div>
</div>
<div class="col-xs-8 big-square">
  <a href="#">
    <img src="assets/img/neghab-03.JPG" />
  </a>
</div>

我的jquery代码是:

$(function(){
    $(".v-text").height(($(this).next().height()+"px"));
});

我的代码中有超过10个不同高度的div。我希望他们所有人都有下一个div高度。我的代码没有用。你能帮我解决一下我的jquery代码有什么问题吗?

1 个答案:

答案 0 :(得分:2)

代码中的

this并不是特别的。你可能意味着:

$(function(){
    var vtext = $(".v-text");
    vtext.next().height(vtext.height());
});

...这样你就可以在下一个div上调用height作为setter,在v-text div上作为getter调用。另请注意,当值为数字时,您不需要附加px,jQuery会处理它。

重新评论:

  

我有超过10个不同身高的div ....

你应该在问题中提到过。我们可以使用each循环:

$(function(){
    $(".v-text").each(function() {
        var vtext = $(this);
        vtext.next().height(vtext.height());
    });
});

直播示例:

var counter = 3;
var timer = setInterval(function() {
  if (--counter === 0) {
    clearInterval(timer);
    $(".v-text").each(function() {
      var vtext = $(this);
      vtext.next().height(vtext.height());
    });
    $("#countdown").text("done");
  } else {
    $("#countdown").text(counter);
  }
}, 800);
.v-text,
.big-square {
  background-color: #ed0;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<div id="countdown" style="font-weight: bold; color: blue">3</div>
<div class="container">
  <div class="row">
    <div class="col-xs-4 white-bg v-text">
      <div class="">
        <h4>My header</h4>
      </div>
    </div>
    <div class="col-xs-8 big-square">
      <a href="#">
        <img src="https://www.gravatar.com/avatar/ea3e7fb871c61756b961bc56c0478809?s=32&d=identicon&r=PG&f=1" />
      </a>
    </div>
  </div>
</div>
<div class="container">
  <div class="row">
    <div class="col-xs-4 white-bg v-text">
      <div class="">
        <h4>My header<br>Bigger</h4>
      </div>
    </div>
    <div class="col-xs-8 big-square">
      <a href="#">
        <img src="https://www.gravatar.com/avatar/ea3e7fb871c61756b961bc56c0478809?s=32&d=identicon&r=PG&f=1" />
      </a>
    </div>
  </div>
</div>
<div class="container">
  <div class="row">
    <div class="col-xs-4 white-bg v-text">
      <div class="">
        <h4>My header<br>Much<br>Bigger</h4>
      </div>
    </div>
    <div class="col-xs-8 big-square">
      <a href="#">
        <img src="https://www.gravatar.com/avatar/ea3e7fb871c61756b961bc56c0478809?s=32&d=identicon&r=PG&f=1" />
      </a>
    </div>
  </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

当然,只有在解析DOM时才会使它们的高度相等,如果加载v-text元素中的图像并更改其高度,或者如果用户调整浏览器大小并更改高度。