使用JavaScript查找图像的宽度,同时将图像添加为css中的背景图像

使用JavaScript查找图像的宽度,同时将图像添加为css中的背景图像,javascript,css,Javascript,Css,必须找到图像的自然宽度、高度 但是图像添加了css作为背景图像 html,正文{ 身高:100%; 保证金:0; } .形象{ 身高:50%; 边框:1px实心橙色; 背景重复:无重复; 背景图片:url'https://unsplash.it/200/300?image=0'; } 见评论: //获取图像 var img=document.querySelector.image; //获取其当前样式 var style=window.getComputedStyle?getComputed

必须找到图像的自然宽度、高度

但是图像添加了css作为背景图像

html,正文{ 身高:100%; 保证金:0; } .形象{ 身高:50%; 边框:1px实心橙色; 背景重复:无重复; 背景图片:url'https://unsplash.it/200/300?image=0'; } 见评论:

//获取图像 var img=document.querySelector.image; //获取其当前样式 var style=window.getComputedStyle?getComputedStyleimg:img.currentStyle; //从中提取URL var match=/url\?[^]+?\/.execstyle.backgroundImage; 如果匹配{ //创建一个“img”` var x=document.createElement'img'; //注意它加载时可能来自缓存 x、 onload=函数{ //现在我们知道了它的自然大小 console.logwidth=+x.width+,height=+x.height; console.lognaturalWidth=+x.naturalWidth+,naturalHeight=+x.naturalHeight; }; //挂接“负载”后设置src x、 src=匹配[1]; } html,正文{ 身高:100%; 保证金:0; } .形象{ 身高:50%; 边框:1px实心橙色; 背景重复:无重复; 背景图片:url'https://unsplash.it/200/300?image=0'; }
您可以像这样使用jQuery获取属性值

var image_width=$.image.width; var image_height=$.image.height


我是从我的手机上发的,所以请原谅格式化的代码

也许img=new Image.src=sth;img.naturalWidth…@Jonasw是的,正在尝试,但没有达到预期的匹配=/url\?[^]+?\/.execstyle.backgroundImage;还有别的办法吗,我会犯这样的错误@bhv:那把小提琴没有使用上面的工作代码。我的建议是…使用上面的工作代码错误的原因是您没有删除值周围的引号。