简体   繁体   English

如何使用JavaScript在onload上加载图片?

[英]How to load image on onload with javascript?

I am new with HTML and JavaScript. 我是HTML和JavaScript的新手。 I am trying to load image using onload event through JavaScript. 我正在尝试通过JavaScript使用onload事件加载图像。

My code is as below: 我的代码如下:

<script>
 function createImage() {

        ('testimonialhulk').src='photo.jpg';
</script>

and the HTML is HTML是

<body onload="createImage()">

<div class="testimonialhulk">

</div>


</body>
</html>

I have to display image in div tag. 我必须在div标签中显示图像。

This works in my jsfiddle 这在我的jsfiddle中有效

<body onload="createImage();">
    <div id="testimonialhulk">
        Hello
    </div>
</body>

Js: Js:

function createImage() 
{
    var myElement = document.getElementById("testimonialhulk");
    myElement.style.backgroundImage = "url('https://placehold.it/350x150')";
}

JS fiddle https://jsfiddle.net/wuskc68d/1/ JS小提琴https://jsfiddle.net/wuskc68d/1/

Try this 尝试这个

function createImage() {
var par = document.getElementsByClassName("testimonialhulk")[0];
var img = document.createElement('img');
img.src = 'put path here';
par.appendChild(img);
}

or use <div id="testimonialhulk"> 或使用<div id="testimonialhulk">

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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