使用JavaScript获取CSS背景图像的大小? [英] Get the Size of a CSS Background Image Using JavaScript?
本文介绍了使用JavaScript获取CSS背景图像的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用JavaScript来获取CSS引用的背景图片的实际大小(宽度和高度)?
解决方案
是的,我会这样做...
window.onload = function(){
var imageSrc = document
.getElementById('hello')
.style
.backgroundImage
.replace(/ url\(([' )?(。*?)\1\)/ gi,'$ 2')
.split(',')[0];
//我刚刚分手了可读性的换行符
var image = new Image();
image.src = imageSrc;
var width = image.width,
height = image.height;
alert('width ='+ width +',height ='+ height)
}
有些笔记...
-
url()
JavaScript返回以获得正确的图像源。 - 我们需要在
, / code>对象,并将其
src
设置为新图像。 - 然后我们可以读取宽度&
jQuery可能会很少头疼。
Is it possible to use JavaScript to get the actual size (width and height in pixels) of a CSS referenced background image?
解决方案
Yes, and I'd do it like this...
window.onload = function() {
var imageSrc = document
.getElementById('hello')
.style
.backgroundImage
.replace(/url\((['"])?(.*?)\1\)/gi, '$2')
.split(',')[0];
// I just broke it up on newlines for readability
var image = new Image();
image.src = imageSrc;
var width = image.width,
height = image.height;
alert('width =' + width + ', height = ' + height)
}
Some notes...
- We need to remove the
url()
part that JavaScript returns to get the proper image source. We need to split on,
in case the image has multiple backgrounds. - We make a new
Image
object and set itssrc
to the new image. - We can then read the width & height.
jQuery would probably a lot less of a headache to get going.
这篇关于使用JavaScript获取CSS背景图像的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文