Set “min-width:100%” for images larger than 400px? JS or CSS

问题: I am trying to set up a JS/jQuery/CSS solution to select images larger than 400px and set them to be the full width of the container (min-width: 100%). However, it should...

问题:

I am trying to set up a JS/jQuery/CSS solution to select images larger than 400px and set them to be the full width of the container (min-width: 100%).

However, it should not apply to images smaller than 400px to avoid selecting really small ones or thumbnails. Normally, I'd just use classes, but the markup is generated by an old wiki intranet system which doesn't give users the ability to set classes.

Any help would be appreciated.

.container {
  width: 700px;
  border: solid 1px red;
}

.container img {
  border: solid 1px green;
  max-width: 100%;
  height: auto;
  display: block;
  margin: auto auto;
}
<div class="container">
  <img src="https://via.placeholder.com/140x100" />
  <img src="https://via.placeholder.com/500x100?text=Should_be_full_width" />
</div>


回答1:

$(function() {
  $('img').each((i, img) => {
    let width = parseInt($(img).css('width'));
    if (width > 400) {
      $(img).css('width', '100%');
    }
  });
});
.container {
  width: 700px;
  border: solid 1px red;
}

.container img {
  border: solid 1px green;
  max-width: 100%;
  height: auto;
  display: block;
  margin: auto auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <img src="https://via.placeholder.com/140x100" />
  <img src="https://via.placeholder.com/500x100?text=Should_be_full_width" />
</div>


回答2:

This would work

var images = $("img")

for (let i = 0; i < images.length; i++) {
    if (images[i].width >= 400) {
    images[i].style.minWidth = "100%";
  }
}

回答3:

You can use the naturalWidth property after the images are loaded (use the window load event) and manually add a class (use classList).

window.addEventListener('load', () => {
  const images = document.querySelectorAll('img');
  for (let image of images) {
    if (image.naturalWidth >= 400) {
      image.classList.add('full-width');
      // or set the style directly if you have to
      // image.style.minWidth = '100%';
    }
  }
});
.container {
  width: 700px;
  border: solid 1px red;
}

.container img {
  border: solid 1px green;
  max-width: 100%;
  height: auto;
  display: block;
  margin: auto auto;
}

.full-width {
  min-width: 100%;
}
<div class="container">
  <img src="https://via.placeholder.com/140x100" />
  <img src="https://via.placeholder.com/500x100?text=Should_be_full_width" />
</div>

  • 发表于 2020-06-27 20:33
  • 阅读 ( 146 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除