onload()方法只能在body标签中调用吗?怎么调用多个多个方法?
第一个问题:
onload()方法并非只能在body标签中调用的,还可以在js中用window.onload = function() {函数名};来调用;另外img等标签也支持onload方法。
支持onload方法的标签有:<body>, <frame>, <frameset>, <iframe>, <img>, <link>, <script>
window.onload = function(){drawRed()};
<img id="img1" src="src/img1.jpg" onload="changeImg()"></img>
第二个问题:
同时调用多个方法时,可以在body中使用<body onload="函数名1;函数名2;函数名3;......">的方式:
<body onload="drawBlack();drawRed()">
举例说明一下:
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>HTML5画布</title> <!--利用js在画布上绘制图案--> <script type="text/javascript"> function drawRed() { var c = document.getElementById("myCanvas"); var cxt = c.getContext("2d"); cxt.fillStyle = "#FF0000"; cxt.beginPath(); cxt.arc(70, 18, 15, 0, Math.PI * 2, true); cxt.closePath(); cxt.fill(); } function drawBlack() { var c = document.getElementById("myCanvas"); var cxt = c.getContext("2d"); cxt.fillStyle = "#000000"; cxt.beginPath(); cxt.arc(170, 18, 15, 0, Math.PI * 2, true); cxt.closePath(); cxt.fill(); } function changeImg() { document.getElementById("img1").src = "src/bg.jpg"; } // onload()方法的调用方式之一 window.onload = function(){drawRed()}; window.onload = function(){drawBlack()}; </script> </head> <!--onload()方法的调用方式之二--> <body onload="drawBlack();drawRed()"> <!--定义一块画布--> <canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;"> Your browser does not support the canvas element. </canvas> <img id="img1" src="src/img1.jpg" onload="changeImg();drawBlack();drawRed()"></img> </body> </html>
执行效果如下: