问题
I am trying to get image in a <div>
using onclick
.
Now I am getting the text on click. but I want to get the image in div on click...
How can i do this...?
Here is code I have implemented,,
Code:
<script>
function myFunction()
{
document.getElementById("surprise").innerHTML=images/aftersurprise.png;
}
</script>
When I click on element I should get the aftersurprise.png
image on surprise element...
回答1:
use
document.getElementById("surprise").innerHTML="<img src='images/aftersurprise.png' />";
回答2:
You are giving the image url to the innerHTML
of div element. To add an image there you have to do something like this
document.getElementById("surprise").innerHTML="<img src='images/aftersurprise.png' />";
Or why are you not going with jquery
, it's very easy with that like
$('#surprise').append("<img src='images/aftersurprise.png' />");
回答3:
Just giving the image url will not add the image inside the div. You have to specify it using img
tag.
or dynamically create it using the following code and append to the div
var img = document.createElement('img')
img.src = 'images/aftersurprise.png';
document.getElementById('surprise').appendChild(img);
回答4:
Try this
(function() {
var oDiv = document.getElementById('surprise');
oDiv.addEventListener('click', function() {
this.setAttribute('style', 'background-image: images/aftersurprise.png');
}, false);
})();
It sets the image as background image of the div
回答5:
img = document.createElement("img");
img.setAttribute('src','https://www.google.co.in/images/srpr/logo11w.png');
document.getElementById("surprise").appendChild(img);
here u can set ur image src
回答6:
As I understand, your issue is that all the content is displayed on a new/ existing page except image...! If that is so, you just need to put some delay when calling your JS function. Try this:
function Myfunction ()
{
setTimeout(load, 1000); //this delay will allow browser to load complete image
function load()
{
var divToPrint = document.getElementById('surprise');
var popupWin = window.open('', '_blank','width=1000, height=800, location=no, left=200px');
//popupWin.document.open(); //needed when popup required
popupWin.document.write('<html><body onload="window.print()">' + divToPrint.innerHTML + '</html>');
popupWin.document.close();
}
}
回答7:
$('#divname').append or prepend("<img src='pathOfImages.jpg'/>");
here use only one attributes like append , another prepend >(before content)
来源:https://stackoverflow.com/questions/19331606/onclick-add-image-to-div