【问题标题】:Is there any way to select all images of a certain size in Javascript? [closed]有没有办法在 Javascript 中选择所有特定大小的图像? [关闭]
【发布时间】:2019-12-18 15:49:13
【问题描述】:

我想选择网页上大于特定尺寸(例如 200 x 200 像素)的所有图像。有没有办法在 Javascript 中做到这一点?

【问题讨论】:

  • 是的,检查所有图像标签的图像尺寸
  • @JaromandaX 这将告诉您正在渲染的图像大小,但不一定是本机图像大小。
  • 1) 等待所有图像完成加载。 2) 找到所有<img> 元素。 3) 使用naturalWidth / naturalHeight 属性根据图像尺寸过滤该集合
  • @ScottMarcus - 正确的 - OP 写了零代码,所以我提出了一个零代码的建议 - 似乎很公平 - Phil 似乎给出了伪代码,这比 OP 更努力
  • @Phil - 是的,是任何维度超过 200、两个维度超过 200、总面积超过 40000 的标准......但仍然 - 模糊的问题,充其量完全没有研究工作

标签: javascript image dom css-selectors getelementsbytagname


【解决方案1】:

试试这个。

let img = document.querySelectorAll('img'),
  len = img.length,
  counter = 0;

[].forEach.call(img, function(img) {
  img.addEventListener('load', () => {
    counter++;
    if (counter === len) {
      console.log('all images loaded at ' + new Date().toLocaleTimeString());
      check(); // call automatically without user interaction
    }
  }, false);
});

check(); // just to show it works only after all image loads

function check(size) {
  if (counter !== len) {
    console.log('waiting for images to load at ' + new Date().toLocaleTimeString());
    return;
  }
  let result = {};
  img.forEach(e => {
    if (!result[e.naturalHeight + 'x' + e.naturalWidth]) {
      result[e.naturalHeight + 'x' + e.naturalWidth] = [];
    }
    if (size && e.naturalHeight >= size && e.naturalWidth >= size) {
      result[e.naturalHeight + 'x' + e.naturalWidth].push(e.src);
    } else if (typeof(size) == 'undefined') {
      result[e.naturalHeight + 'x' + e.naturalWidth].push(e.src);
    }
  });
  console.log(result);
}
.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 1em;
}

img {
  max-width: 100%;
}
<button onclick="check()">Check Size</button>
<button onclick="check(600)">Check Size > 600</button>
<div class="container">
  <img src="https://dummyimage.com/400x400/000/fff" />
  <img src="https://dummyimage.com/600x400/000/fff" />
  <img src="https://dummyimage.com/400x400/000/fff" />
  <img src="https://dummyimage.com/600x400/000/fff" />
  <img src="https://dummyimage.com/600x600/000/fff" />
</div>

【讨论】:

  • 在尝试获取图像尺寸之前,应确保图像已完全加载
  • 另外,我没有投反对票,但这不会帮助 OP 找到超过一定尺寸的图像
  • 已编辑帖子。 OP没有说什么时候触发这个功能。
  • 我的意思是,在执行过滤之前,您至少需要等待图像加载。如果我在图片加载之前点击你的按钮,结果会很糟糕。
  • 是的,当然,你是对的。我确实是这样想的,但 OP 没有提到任何内容,但让我也围绕这种情况做一些事情。谢谢@Phil
猜你喜欢
  • 2011-11-28
  • 2016-12-08
  • 2017-04-30
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2020-10-09
  • 2021-04-28
  • 2018-05-16
相关资源
最近更新 更多