最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Display an image in a div with javascript? - Stack Overflow

programmeradmin2浏览0评论

my js is not good, but I'm thinking I'm going to need to use the getElementbyId some think like:

if (a == ‘tick’)
document.getElementById(‘imageDiv’) = tick.gif
else
document.getElementById(‘imageDiv’) = cross.gif
<div id="imageDiv"></div>

but is does not work.

my js is not good, but I'm thinking I'm going to need to use the getElementbyId some think like:

if (a == ‘tick’)
document.getElementById(‘imageDiv’) = tick.gif
else
document.getElementById(‘imageDiv’) = cross.gif
<div id="imageDiv"></div>

but is does not work.

Share Improve this question asked Mar 7, 2012 at 6:39 user1234315user1234315 1
  • @Black_Crown imageDiv is a div, setting src for it will not display any image. – kirilloid Commented Mar 7, 2012 at 6:46
Add a comment  | 

4 Answers 4

Reset to default 12

Use this, it should work.

<script type="text/javascript">
function image(thisImg) {
    var img = document.createElement("IMG");
    img.src = "images/"+thisImg;
    document.getElementById('imageDiv').appendChild(img);
}
if (a == 'tick') {
    image('tick.gif');
} else {
    image('cross.gif');
}
</script>
<div id="imageDiv"></div>

Try this instead:

document.getElementById('imageDiv')
    .innerHTML = '<img src="imageName.png" />';

Or you can create image element dynamically like this:

var par = document.getElementById('imageDiv');
var img = document.createElement('img');
img.src = 'put path here';
par.appendChild(img);

Note also that you should use single quotes or double quotes not character for strings.


So here is how your code should be:

var imgName = a === 'tick' ? 'tick.gif' : 'cross.gif';
document.getElementById('imageDiv')
    .innerHTML = '<img src="' + imgName + '" />';

Or alternatively:

var imgName = a === 'tick' ? 'tick.gif' : 'cross.gif';
var par = document.getElementById('imageDiv');
var img = document.createElement('img');
img.src = imgName;
par.appendChild(img);

Or if you want apply your image to div background, then this is what you need:

var imgName = a === 'tick' ? 'tick.gif' : 'cross.gif';
document.getElementById('imageDiv').style.backgroundImage = 'url('+ imgName +')';

To display image in a div you must set it as background image:

document.getElementById(‘imageDiv’).style.backgroundImage = 'url(tick.gif)';
document.getElementById('imageDiv').innerHTML = 
 '<img src="' + (a == 'tick'?'tick':'cross') + '.gif">';
发布评论

评论列表(0)

  1. 暂无评论