jquery - 使用百分比和媒体查询的宽度时,设置 div 高度以匹配 div 宽度

标签 jquery html css css-float media-queries

我有一个 div 网格,需要更改高度以匹配 div 的宽度。我已经习惯了媒体查询和 jquery 来实现这一点,但是在 jquery 运行之后,并不是所有的 div 都是相同的高度。我在 jquery 中遗漏了什么吗?

JQuery

var setFeedItem = function () {
  console.log($(this).css('width'));
  $(this).css('height', $(this).width());
};

$('#feed .feed_item').each(setFeedItem);
$(window).resize(function () {
  $('#feed .feed_item').each(setFeedItem);
});

CSS:

.feed_item {
  overflow: hidden;
  margin: 0;
  padding: 0 !important;
  position: relative;
  float: left;
  height: 100px;
}
.feed_item img {
  width: 100%;
  height: 100%;
}
@media screen and (max-width: 2500px) {
  .feed_item {
    width: 10%;
  }
}
@media screen and (max-width: 2000px) {
  .feed_item {
    width: 12.5%;
  }
}
@media screen and (max-width: 1500px) {
  .feed_item {
    width: 20%;
  }
}
@media screen and (max-width: 1200px) {
  .feed_item {
    width: 25%;
  }
}
@media screen and (max-width: 900px) {
  .feed_item {
    width: 33.33333333%;
  }
}
@media screen and (max-width: 700px) {
  .feed_item {
    width: 50%;
  }
}
@media screen and (max-width: 480px) {
  .feed_item {
    width: 100%;
  }
}
@media screen and (max-width: 320px) {
  .feed_item {
    width: 100%;
  }
}

HTML:

<div id="feed">
  <div class="feed_item"><img src="images/rand1.jpg" /></div>
  <div class="feed_item"><img src="images/rand3.jpg" /></div>
  <div class="feed_item"><img src="images/rand2.jpg" /></div>
  <div class="feed_item"><img src="images/rand1.jpg" /></div>
  <div class="feed_item"><img src="images/rand4.jpg" /></div>
  <div class="feed_item"><img src="images/rand2.jpg" /></div>
  <div class="feed_item"><img src="images/rand1.jpg" /></div>
  <div class="feed_item"><img src="images/rand4.jpg" /></div>
  <div class="feed_item"><img src="images/rand3.jpg" /></div>
</div>
<div style="clear:both"></div>

可能是媒体查询干扰了 jQuery,但任何帮助都会很好,因为这会不断破坏我的布局。

最佳答案

如果我的理解是正确的,你想要方形响应 block ?在这种情况下,您不需要 jQuery。您可以在元素上使用底部填充,为它们提供“响应式”高度。

.feed_item{
  width:20%;
  background:red;
  padding-bottom:20%;
}

如果您想要这些 block 中的图像缩放到 .feed_item 的大小,您可以将 position:relative 添加到 .feed_item 并将 img 绝对定位。看看这支笔:

http://codepen.io/SamP/pen/GqrypX

关于jquery - 使用百分比和媒体查询的宽度时,设置 div 高度以匹配 div 宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38027218/

相关文章:

javascript - 使用 jQuery 链接到 Accordion 中的部分

javascript - 如何使用 javascript/jquery 获取数组中选中和未选中的复选框值

php - 触发 jQuery 抓取 HTML 并保存到数据库的按钮

iphone - 将 HTML <Tag> 解析为 ios

css - 我编辑了一些 CSS,现在我的页面奇怪地变宽了两倍

php - 将类添加到 Wordpress 函数

javascript - jPlayer 2.2.0 : display track title in separate div on page load

jquery - 为什么Application_ResolveRequestCache的持续时间很长?

javascript - CSS 中::after 和::before 的区别

html - 在css中定位两个元素