2017-07-24 61 views
0

我使用JQuery使DIV具有与宽度相同的高度并作出响应更新。DIV匹配其他div与不同长宽比的高度与JQuery响应式

我还需要制作另一个DIV(具有不同的宽高比)与方格保持相同的高度。

See fiddle

调整浏览器窗口,即使黑DIV应匹配的红色和白色的div的高度。

function update() { 
 
    $(".match").each(function() { 
 
    var height = $(this).width(); 
 
    console.log(height); 
 
    $(this).css('height', height + 'px'); 
 
    }); 
 
} 
 

 
update(); 
 
$(window).resize(function() { 
 
    update(); 
 
});
.main { 
 
    width: 100%; 
 
    max-width: 1200px; 
 
    margin: 0 auto; 
 
    height: 2000px; 
 
    background-color: #333333; 
 
} 
 

 
.square { 
 
    width: 10%; 
 
    background-color: #ffffff; 
 
    float: left; 
 
} 
 

 
.oblong { 
 
    width: 40%; 
 
    float: left; 
 
    max-height: 150px; 
 
    background-color: #000000; 
 
} 
 

 
.color { 
 
    background-color: red !important; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<body> 
 
    <div class="main"> 
 
    <div class="oblong match"></div> 
 
    <div class="square match"></div> 
 
    <div class="square match color"></div> 
 
    <div class="square match"></div> 
 
    <div class="square match color"></div> 
 
    <div class="square match"></div> 
 
    <div class="square match color"></div> 
 
    </div>

+0

所以你要输出 – Bhargav

+0

什么?如果我理解你的权利,你要到div“椭圆形匹配” rezise像其他尺寸相同,当你reszise窗口? – reporter

回答

0

只是分配循环的变量之外,那么您将在指定高度的值变循环并使用它来更新元素的高度,如下所示:

var height = 0; 
function update() { 
$(".match").each(function() { 
    height = $(this).width(); 
    console.log(height); 
    $(this).css('height',height + 'px'); 
}); 
$(".oblong").css('height',height + 'px'); 
} 
0

我在盒子周围添加了一个包装并将其显示为flexbox。我从黑匣子中删除了类match,因此高度将不会重新计算,而是自动分配。

function update() { 
 
    $(".match").each(function() { 
 
    var height = $(this).width(); 
 
    console.log(height); 
 
    $(this).css('height', height + 'px'); 
 
    }); 
 
} 
 

 
update(); 
 
$(window).resize(function() { 
 
    update(); 
 
});
.main { 
 
    width: 100%; 
 
    max-width: 1200px; 
 
    margin: 0 auto; 
 
    height: 2000px; 
 
    background-color: #333333; 
 
} 
 

 
.toprow { 
 
    display: flex; 
 
} 
 

 
.square { 
 
    width: 10%; 
 
    background-color: #ffffff; 
 
} 
 

 
.oblong { 
 
    width: 40%; 
 
    max-height: 150px; 
 
    background-color: #000000; 
 
} 
 

 
.color { 
 
    background-color: red !important; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="main"> 
 
    <div class="toprow"> 
 
    <div class="oblong"></div> 
 
    <div class="square match"></div> 
 
    <div class="square match color"></div> 
 
    <div class="square match"></div> 
 
    <div class="square match color"></div> 
 
    <div class="square match"></div> 
 
    <div class="square match color"></div> 
 
    </div> 
 
</div>