Javascript练习
1、时钟
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Javascript时钟</title> <script type="text/javascript"> function currenttime(){ setInterval(function (){ var now = new Date(); var str =''; str += now.getYear()+1900+'年'; str += now.getMonth()+1+'月'; str += now.getDate()+'日'; str += now.getHours()+'时'; str += now.getMinutes()+'分'; str += now.getSeconds()+'秒'; document.getElementById('left').innerHTML=str; },1000); } </script> </head> <body> <p> <input type="button" value="当前时间" onclick="currenttime();"/> </p> <h2 id="left"></h2> </body> </html>
此处出现Cannot set property 'innerHTML' of null 错误,原因是设置的编号与实际的编号不符,少了单引号。
2、创建动态样式
使用DOM样式对象创建一个允许控制页面文本颜色的页面。
style.js
function changehead(){ i=document.form1.heading.selectedIndex; headcolor = document.form1.heading.options[i].value; document.getElementById("head1").style.color=headcolor; } function changebody(){ i=document.form1.body.selectedIndex; doccolor = document.form1.body.options[i].value; document.getElementById("p1").style.color=doccolor; }
注意:在函数内声明创建一个外围变量名相同的变量时,必须使用var关键字
ControlStyle.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Controlling Styles with JavaScript</title> <script type="text/javascript" src="styles.js"></script> </head> <body> <h1 id="head1">Controlling Styles with JavaScript</h1> <hr> <p id="p1"> Select the color for paragrahs and heading using the form below. The colors you specified will be dynamically changed in this document. The change occurs as soon as you changge the value iof either of the drop-down lists in the form. </p> <form name="form1"> <b>Heading color:</b> <select name="heading" onchange="changehead();"> <option value="black">Black</option> <option value="red">Red</option> <option value="blue">Blue</option> <option value="green">Green</option> <option value="yellow">Yellow</option> </select> <br> <b>Body text color:</b> <select name="body" onchange="changebody();"> <option value="black">Black</option> <option value="red">Red</option> <option value="blue">Blue</option> <option value="green">Green</option> <option value="yellow">Yellow</option> </select> </form> </body> </html>