【问题标题】:Set "min-width:100%" for images larger than 400px? JS or CSS为大于 400 像素的图像设置“最小宽度:100%”? JS 或 CSS
【发布时间】:2020-10-12 21:10:58
【问题描述】:

我正在尝试设置一个 JS/jQuery/CSS 解决方案来选择大于 400 像素的图像并将它们设置为容器的全宽 (min-width: 100%)。

但是,它不应应用于小于 400 像素的图像,以避免选择非常小的图像或缩略图。通常,我只会使用类,但标记是由旧的 wiki 内部网系统生成的,它不给用户设置类的能力。

任何帮助将不胜感激。

.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>

【问题讨论】:

  • 当你说“no classes”时你的意思是你不能使用jquery函数'addClass'?
  • 它占用了 .container 的大小。将 .container 设为全尺寸,图像将随之而来。
  • @JohnSims 不,只是它们不会出现在原始生成的 HTML 中。

标签: javascript jquery css image


【解决方案1】:

您可以在图像加载后使用naturalWidth 属性(使用窗口load 事件)并手动添加一个类(使用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>

【讨论】:

    【解决方案2】:

    $(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>

    【讨论】:

    • 这仅在您的图像已缓存时运行。 $(function() { 代码在 DOMContentLoaded 上运行,这发生在加载图像之前,因此宽度将始终为 0,并且永远不会应用样式。
    【解决方案3】:

    这样就可以了

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

    【讨论】:

    猜你喜欢
    • 2011-08-06
    • 2014-08-03
    • 2018-09-16
    • 2018-10-19
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    相关资源
    最近更新 更多