简体   繁体   中英

HTML image not showing

I have been looking around for a solution to this problem but I am badly stuck. I am declaring a div inside the html file to hold an image, and then dynamically add the image path in Javascript. But no image shows. When I declare both the div and the image path, then the image shows, however, I would prefer no to go this route.

The html looks like this:

 <div id="left" class="photos"></div>

and the Javascript like this:

document.getElementById('left').src = "images/1001.jpg";

What might be the issue here? Might there be some underlying mechanism that I am not aware of?

HTML 需要<img />标签来显示图像。

<img id="left" class="photos" />

<img> tags have 'src' attribute. <div> tags - don't. Either switch to <img> :

<img src='my/image.png' />

Or use CSS background property:

div {
   background-image:url('my/image.png');
   /* Div element won't adjust its size to contain an image, so width and
      height properties might be necessary, depending on your intentions. */
   width: 100px;
   height: 100px;
}

As has been noted, you're trying to set the src attribute on a div . But you also said you wanted to dynamically add an image to that div ?

function setImage(url) {
    var div = document.getElementById('left');
    var imgs = document.getElementsByTagName('img');

//  if there are no images
    if(imgs.length===0) {
    //  create one
        var img = document.createElement('img');
    //  set the src
        img.setAttribute('src',url);
    //  put it in the div
        div.appendChild(div);
    }
//  otherwise
    else {
    //  set the src of the first image
        imgs[0].src = url;
    }
}

if you want to use just javascript, can you use that function:

function showP(el,pic) {
    document.getElementById(el).style.background = 'url(' + pic + ')';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM