繁体   English   中英

获得高度并应用于每个元素失败?

[英]get height and apply to each element failed?

 $.each($('.box'), function () {
     var heightOfBox = $(this).height();
     console.log(heightOfStory);
     $.each($('.line'), function () {
         $(this).css('height', heightOfBox + 'px');
     });
 });

我有一组高度不同的元素,我想将其设置为另一组。 上面的代码失败了,因为它得到了最后一个元素的高度,而不是每个元素的高度。

http://jsfiddle.net/vmxrca1d/1/

 $.each($('.box'), function (i, val) { var heightOfBox = $(this).height(); $(".line").eq(i).css('height', heightOfBox + 'px'); }); 
 .box { background:red; width:10px; margin:10px; } .line { background:blue; width:10px; margin:10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box" style="height:10px;">1</div> <div class="box" style="height:22px;">1</div> <div class="box" style="height:40px;">1</div> <div class="line">1</div> <div class="line">1</div> <div class="line">1</div> 

使用eq()

 $.each($('.box'), function (i, val) {
     $(".line").eq(i).css('height', $(this).height() + 'px');

 });

使用eqindex设置相应元素的高度;

// Iterate over each of the element having box as class
$('.box').each(function (i, val) {
    $('.line').eq(i).height($(this).height());
    // Get the index of this element
    // Set the height of the corresponding element to the current element height
});

演示版

尝试这个..

$.each($('.box'), function (i,d) {
  var heightOfBox = $(d).height();
  console.log(heightOfBox);
$('.line:eq('+ i +')').css('height', heightOfBox + 'px');
});

在这里工作小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM