如何使用 jQuery 检测网页上的每个背景图像?
是否可以使用 jQuery 查找页面上的所有背景图像? 我最初的计划是使用:循环遍历每个元素
jQuery("*").each(function() { ... });
,然后检查每个元素是否具有为 .css("background-image") 设置的属性
但这似乎不起作用。 jQuery("*")
看起来性能不太好。
有更好的办法吗?
Is it possible to use jQuery to find all the background images on a page?
My original plan was to loop through every element using:
jQuery("*").each(function() { ... });
and then check whether each element had a property set for .css("background-image")
However this doesn't seem to work. jQuery("*")
doesn't seem very performant.
Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这对我有用:
和jquery:
控制台日志分别输出image1.jpg和image2.jpg。
不,使用 * 选择器非常非常慢。它实际上会检查所有内容(甚至是非常非常不可能有背景图像的内联元素。您最好选择单个标签类型(例如 div)或按类或 id 进行搜索。这些将比 * 选择器更有效。
祝你好运。
This works for me:
and the jquery:
The console log outputs image1.jpg and image2.jpg, respectively.
And no, using the * selector is very, very slow. It literally checks everything (even inline elements that are very, very unlikely to have background images. You would be better off selecting individual tag types (like divs) or searching by class or id. Those will be much more efficient than the * selector.
Good luck.
虽然我意识到这个问题已经得到解答,并且有一个可接受的答案,但似乎值得指出的是,当前接受的解决方案只会可靠地通知您使用 in- 设置的
background-image
。 linestyle
属性。要访问通过外部样式表分配的元素的背景图像,以下内容更可靠:
JS Fiddle 演示。
然而,一种更新的方法如下:
JS Fiddle 演示。
参考文献:
Array.prototype.filter ()
。Array.prototype.map()
。Array.prototype.push()
。CSSStyleDeclaration.getPropertyValue()
。document.getElementsByTagName()
。document.querySelectorAll()
。...
) 语法。window.getCompulatedStyle()
。While I realise that this question has already been answered, and has an accepted answer, it seems worth pointing out that the currently-accepted solution will only reliably inform you of
background-image
s set using the in-linestyle
attribute.to access those
background-image
s of elements that are assigned via external style sheets the following is more reliable:JS Fiddle demo.
A rather more up-to-date approach, however, would be the following:
JS Fiddle demo.
References:
Array.prototype.filter()
.Array.prototype.map()
.Array.prototype.push()
.CSSStyleDeclaration.getPropertyValue()
.document.getElementsByTagName()
.document.querySelectorAll()
....
) syntax.window.getComputedStyle()
.您可以尝试使用属性包含单词选择器:
$('*[style~="background-image"]')
You could try the attribute contains word selector:
$('*[style~="background-image"]')