使用javascript设置图像源和背景图像 [英] Set image source and background image with javascript

查看:185
本文介绍了使用javascript设置图像源和背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过很多其他帖子,我想我使用的是完全符合语法的建议。但是,我没有看到图像出现。我有一个 jsfiddle 。这是一个jsfiddle问题吗?

I've looked at many other posts and I think I'm using the exact syntax suggested. However, I'm not getting the images to show up. I have a jsfiddle. Is it a jsfiddle issue? It's also not working on a website I'm working on.

<div id="divtest">Hello</div>
<img id="imgtest" />
<img id="imgreal" src="http://www.premiumbeat.com/blog/wpcontent/uploads/2012/12/free.jpeg" />

var string = "url('http://www.premiumbeat.com/blog/wpcontent/uploads/2012/12/free.jpeg')";
alert(string)
document.getElementByID("divtest").style.backgroundImage = string;
document.getElementByID("imgtest").src = string;


推荐答案

两个小问题:


  1. getElementByID 不是一个函数; getElementById 是。

  1. getElementByID is not a function; getElementById is.

网址格式对于图片来源和背景图片是不同的。尝试这样:

var string =' http://www.premiumbeat.com/blog/wp-content/uploads/2012/12/free.jpeg ';
document.getElementById(divtest)。style.backgroundImage =url('+ string +');
document.getElementById(imgtest)。src = string;

The format for a url is different for an image source and a background image. Try this: var string = 'http://www.premiumbeat.com/blog/wp-content/uploads/2012/12/free.jpeg'; document.getElementById("divtest").style.backgroundImage = "url('" + string + "')"; document.getElementById("imgtest").src = string;

这篇关于使用javascript设置图像源和背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆