简体   繁体   中英

add image as div with javascript

I am trying to add an image as an element into my webpage. I am unable to do so. There are instructions on how to preview an image, but I was unable to find a solution.

What I want it to do is to add a div with an image into the webpage and keep loading it with different images. So after I add image 1, I would load image 2 under image 1 in the same webpage.

html body code:

<input type='file' id='getval' /><br/><br/>
<span onclick="readURL()" class="addBtn">Add</span>
<div id="myUL"></div>

javascript code:

<script type="text/javascript">
    // grabs image
    var file = document.createElement('image');
    file.src = document.getElementById('getval').files[0];
    // creates div & assigns id
    var div = document.createElement('div');
    div.id = 'item';

    // adds file to div
    file.type = 'image';
    div.appendChild(file);

    //adds item
    document.getElementById("myUL").appendChild(div);
}
</script>

edit1* I think adding the output of the code I want to display would be better inside the html document.

javascript generates html code inside document:

 <div style="background-image":url("image");"><div>

Here you go, although pay attention to the comment at line 3.

<script type="text/javascript">
var file = document.createElement("img");
file.setAttribute("src", document.getElementById('getval').files[0]); //You can use HTML5 File API here
file.setAttribute("height", "250");
file.setAttribute("width", "250");
var divTocreate = document.createElement('div');
divTocreate.id = 'item';
divTocreate.appendChild(file);
document.getElementById("myUL").appendChild(divTocreate);
</script>

You can use this script

 count = 0; function viewImage(){ var imagefile = document.querySelector('#image'); if (imagefile.files && imagefile.files[0]) { var reader = new FileReader(); reader.onload = function (e) { var content = '<img id="temp_image_'+count+'" style="border: 1px solid; width: 107px;height:107px;" >'; document.querySelector('#all_images').innerHTML += content; document.querySelector('#temp_image_'+count).setAttribute('src', e.target.result); }; reader.readAsDataURL(imagefile.files[0]); this.imagefile = imagefile.files[0]; count++; }else{ console.log("Image not selected"); } } 
 <div id="all_images"> </div> <input id="image" name="image" type="file" onChange="viewImage()"> 

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