document.getElementsByTagName('img') ,如何只获取png图像?
我试图只从 dom 获取具有 png 属性的图像,有人知道如何做到这一点吗?
I am trying to only get images with the png attribute from the dom, does anyone know how to this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有安全的方法可以做到这一点。浏览器不会在任何地方公开已加载的图像类型。此外,您甚至无法保证图像 URL 具有正确的文件扩展名,因为
http://example.com/some/image
是一个非常有效的 URL。您可以使用“attribute contains”CSS 选择器和
querySelectorAll
以及支持它的浏览器来获得近似值:这会找到所有带有
.png
的img
元素在其src
属性中的某处。请注意,这很容易受到误报和漏报的影响。此方法在 IE 7 及以下版本中不起作用。
There is no safe way of doing this. The browser does not expose anywhere what type of image has been loaded. Moreover, you can't even guarantee that the image URL will have the correct file extension, because
http://example.com/some/image
is a quite valid URL.You can get an approximation using the "attribute contains" CSS selector with
querySelectorAll
with browsers that support it:That finds all
img
elements with.png
somewhere in theirsrc
attribute. Note that this is vulnerable both to false positives and to false negatives.This method will not work in IE 7 or below.
要迭代图像并返回具有以 .png 结尾的 src 属性的图像:
pngs 是 src 以 .png 结尾的图像数组并且几乎可以在所有支持脚本的浏览器中使用。
如果您想要使用 querySelectorAll (如果可用)和对图像进行简单循环(如果不可用)的东西,那么以下内容应该适合(根据 lonesomeday 的 ansewr):
您可能会返回一个 NodeList 或一个数组,但如果您想要做的只是迭代它那么就可以了。否则,您需要将 qSA 分支的结果转换为数组,这又需要几行代码。
To iterate over the images and return those with a src property ending in .png:
pngs is an array of images whose src ends in .png and will work in nearly every browser that ever supported scripting.
If you want something that uses querySelectorAll if available and a simple loop over images if not, then the following should suit (per lonesomeday's ansewr):
You might get back a NodeList or an array, but if all you want to do is iterate over it then that's ok. Otherwise you'll need to convert the result of the qSA fork to an array, which is a couple more lines of code.