$( window ).ready(function() {
if ($( document ).width() > 576) {
$('.col').each(function() {
var parentHeight = $(this).parent().height();
$(this).height(parentHeight);
});
}
else {console.log("Mobile.")}
});
这是我的代码。我有这样的html:
<div class="row">
<div class="col col-8"><img src="assets/images/vizhanyo-erdeklodes.jpg" alt="Egy mém, ami neked nem tölt be." class="col-img"></div>
<div class="col col-8"><img src="assets/images/mor-pluszmunka.jpg" alt="Egy mém, ami neked nem tölt be." class="col-img"></div>
<div class="col col-8"><img src="assets/images/fizika-peldatar.jpg" alt="Egy mém, ami neked nem tölt be." class="col-img"></div>
</div>
<div class="row">
<div class="col col-8"><img src="assets/images/vizhanyo-szep-almokat.jpg" alt="Egy mém, ami neked nem tölt be." class="col-img"></div>
<div class="col col-8"><img src="assets/images/vizhanyo-art.jpg" alt="Egy mém, ami neked nem tölt be." class="col-img"></div>
<div class="col col-8"><img src="assets/images/mor-az-on-otthonaban.jpg" alt="Egy mém, ami neked nem tölt be." class="col-img"></div>
</div>
问题是,排的内部并不总是完美的。有时,所有的行(除第一个除外)变为〜5px高。为什么?您可以在www.imarkus.me/2020b
可能是因为row
高度是由内部图像定义的,在您的JS启动时可能没有加载。
有不同的解决方案。宽松的人是使用https://github.com/liabru/jquery-matth-height
您还可以使用FlexBox:https://osvaldas.info/flexbox-基于-Responsive-equal-Height-Height-blocks-with-javascript-fallback不需要JS,但并非所有浏览器都支持此功能。
如果要坚持解决方案:在DIVS上添加resize
侦听器,并在每个大小的大小上调整高度。像
var setHeight = function() {
$('.col').each(function() {
var parentHeight = $(this).parent().height();
$(this).height(parentHeight);
});
}
setHeight(); // initial call
$('.row, .col').on('resize', setHeight);
(未经测试)
编辑向听众添加了col
。
我认为您需要在图像中添加高度和宽度。如果将其添加到样式表。它将每次保持固定尺寸的图像。
img{
width: 50px;
height: 50px
}
如果您需要在屏幕的不同大小上不同的图像。您可以使用@Media标签来实现这一目标。
@media screen and (min-width: 580px) {
img{
width: 20px;
height: 20px
}
}
现在,您的图像的高度和宽度将为20px。
我必须在功能之前使用settimeout。
$( document ).ready(function() {
setTimeout(function() {
if ($( document ).width() > 576) {
$('.col').each(function() {
var parentHeight = $(this).parent().height();
$(this).height(parentHeight);
});
}}, 400)
});
$(window).resize(function(){location.reload();});
,在最后一行,如果我调整了窗口大小以运行函数。