Javascript: image object -> HTML image element

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

The code preloads an image into an image object and then (supposed to) set it to the image element src on HTML:

<!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> 

Why it doesn't work?

回答1:

Try

<!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> 

You can't set a src to an image, you have to set it to the image's src. (PS: Added semicolon at the end and changed .src = oImage to .src = oImage.src)

DEMO



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!