Javascript根据其自身大小按比例调整背景颜色

Javascript根据其自身大小按比例调整背景颜色,javascript,Javascript,我想将背景图像的大小调整为原始大小的30%,然后将其用作元素的背景。我确信我的错误在最后一行的某个地方。 这是我的密码: var img = new Image(); img.src = "wallpaper.jpg"; var a = img.height; var newWidth = (img.width*0.3)); var newHeight = (img.height*0.3)); t.getBody().style.backgroundImage = "url("+img.src

我想将背景图像的大小调整为原始大小的30%,然后将其用作元素的背景。我确信我的错误在最后一行的某个地方。 这是我的密码:

var img = new Image();
img.src = "wallpaper.jpg";
var a = img.height;
var newWidth = (img.width*0.3));
var newHeight = (img.height*0.3));

t.getBody().style.backgroundImage = "url("+img.src+")"; 
t.getBody().style.backgroundSize = "(newWidth)px  (newHeight)px";

background size
属性的值应该类似于
Xpx-Ypx
。尝试将最后一行更改为:

t.getBody().style.backgroundSize = newWidth+"px "+newHeight+"px";

用中间的空格替换newWidth和newHeight值

var img = new Image();
img.src = "wallpaper.jpg";
var a = img.height;
var newWidth = (parseInt(img.width)*0.3);
var newHeight = (parseInt(img.height)*0.3);

t.getBody().style.backgroundImage = "url("+img.src+")"; 
t.getBody().style.backgroundSize = newWidth+"px "+newHeight+"px";

杰出的这正是我错过的,谢谢you@bourax我很乐意帮助你们,但你们接受了一个男人的答案,这是非常令人失望的,这个男人的答案抄袭了我的答案;)@Krzysztof Trzos,不要误入歧途。我实际上是在我的IDE中尝试这一点,除了您的回复之外,它还需要parseInt()来更好地处理数字。我投票赞成你的回答:-)啊,很抱歉没有看到你是第一个:)不管怎样,他投了你一票;)谢谢你们两位!!这正是我错过的,谢谢注意,在检查宽度和高度之前,您需要等待onload事件