将具有相同类的所有元素的div高度设置为与宽度相同

时间:2019-08-16 15:25:01

标签: javascript jquery html css

我想将高度设置为与相同类别的所有容器的宽度相匹配。

我的网站上有许多不同大小的图像。我希望每个图像的div容器的高度都与其自身的宽度相同。

Date  NumRecords ID my_ranks  rank_diff   
2019-03 3   L99887  59          0
2019-04 1   L99887  25          34   
2019-05 1   L99887  22          3
2019-06 2   L99887  46         -24
2019-02 6   L98849  52          0
2019-04 19  L98849  108        -56  
2019-05 18  L98849  126        -18
2019-06 18  L98849  116        10
2019-07 17  L98849  136         -26
2019-08 3   L98849  30          106
<div class="wrapper" style="width:600px">
    <img src="image1.jpg">
</div>
<div class="wrapper" style="width:400px">
    <img src="image2.jpg">
</div>
<div class="wrapper" style="width:200px">
    <img src="image3.jpg">
</div>

我最初尝试以下操作:

.wrapper {
    border-radius: 180px;
    overflow: hidden;
}

img {
    width: 100%;
}

此解决方案行之有效,只是它只影响每个包装器的首次出现。

我还尝试改编了我在StackOverflow上找到的另一个示例(很抱歉,找不到链接),但无济于事:

$(document).ready( function() {
    var wrapper = document.querySelector(".wrapper");
    container.style.height = getComputedStyle(wrapper).width;
} );

任何帮助将不胜感激。

JSFiddle(HTML + CSS):https://jsfiddle.net/h2xnqrL9/

3 个答案:

答案 0 :(得分:3)

这里不需要Java语言。

您可以使用技巧来将任何容器高度设置为其宽度:

.wrapper {position:relative;}
.wrapper:before {
  content: '';
  display: block;
  width: 100%;
  padding-top: 100%; /*trick here*/
}
.wrapper img {
  position:absolute;
  top: 0;
  left: 0;
  width: 100%;
}

任何填充顶部百分比值都是相对于父容器的宽度。 100%表示它将为正方形,50%表示将为其宽度的一半。

当您使用图像比例播放时,这是一个绝妙的技巧;)

我用多余的代码分叉了jsfiddle并添加了轮廓,以便您可以看到方形容器

https://jsfiddle.net/tLw354jm/2/

编辑:此处https://www.w3.org/TR/CSS2/box.html#propdef-padding

答案 1 :(得分:2)

它不适用于您的第一个解决方案是因为document.querySelector(".wrapper")仅返回第一个匹配项。您要做的就是获取所有匹配项,在这种情况下,您可以使用document.querySelectorAll(".wrapper"),然后遍历元素。

使用jQuery,您可以使用以下代码执行此操作:

$(document).ready(function () {
  $(".wrapper").each(function (index, divElem) {
    divElem.style.height = divElem.style.width;
  });
});

答案 2 :(得分:0)

类似这样的东西:

$(document).ready(function() {
  $(".wrapper").each(function() {
    $(this).css('height', $(this).css('width'))
  })
});
.wrapper {
  margin-bottom: 5px;
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper" style="width:600px">
  <img src="https://dummyimage.com/600x600/b0b0b0/000000.jpg">
</div>
<div class="wrapper" style="width:400px">
  <img src="https://dummyimage.com/400x400/b0b0b0/000000.jpg">
</div>
<div class="wrapper" style="width:200px">
  <img src="https://dummyimage.com/200x200/b0b0b0/000000.jpg">
</div>

相关问题