代码将图像预加载到图像对象中,然后(应该)将其设置为 HTML 上的图像元素 src:
<!DOCTYPE html>
<html>
<head>
<script language="javascript">
window.onload = function () {
var oImage = new Image();
oImage.onload = function () {
document.getElementById('myImage').src = oImage;
alert('done');
};
oImage.src = 'image1.jpg';
}
</script>
</head>
<body>
<img id="myImage" src="" />
</body>
</html>
为什么它不起作用?
最佳答案
尝试
<!DOCTYPE html>
<html>
<head>
<script language="javascript">
window.onload = function () {
var oImage = new Image();
oImage.onload = function () {
document.getElementById('myImage').src = oImage.src;
alert('done');
};
oImage.src = 'image1.jpg';
};
</script>
</head>
<body>
<img id="myImage" src="" />
</body>
</html>
你不能为图像设置src,你必须将它设置为图像的src。(PS:在末尾添加分号并更改.src = oImage
到 .src = oImage.src
)
关于Javascript:图像对象 -> HTML 图像元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20954400/