2017-07-24 57 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>