代码将图像预加载到图像对象中,然后(假设)将其设置为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>
为什么它不起作用?
答案 0 :(得分:6)
尝试
<!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:最后添加分号并更改{{ 1}}到.src = oImage
)
<强> DEMO 强>