javascript 细解window对像中一些属性与方法应用
1.setInterval 与 clearInterval方法的简单应用;在text中显示当前的时间。
<input type="text" id="clock" size="35"/><button id="clear">click I clear setInterval</button> <script type="text/javascript"> //写一个方法使显示当前时间 function clock(){ var time = new Date(); document.getElementById("clock").value = time; //得到节点并把当前的时间赋给这个节点的value. } var int = setInterval("clock()",50); //告诉浏览器,我每隔0.5毫秒就往你代码队列中插入执行代码. document.getElementById("clear").onclick = clears; function clears(){ clearInterval(int); }; </script>
说明:在text中显示当前的时间,那么在第一操作时间我们应该创造一下input text 再创建一个button来删除这一个时间控。首先写一个方法clock,这一个方法就是得到内置对象Date的实例并赋值给变量time,得到当函数运行的时间那么我们就应该把这一个时间放到text的value中来完成我们的工作。但是在我们赋给input 的value时大家有没有发现,var time = nw Date();只是在这个函数调用的时间而并没有像真的时钟一样在那里运动着。嘿嘿……人总是很伟大的,会为一些不好的事情作了一系列的努力最终实现。你看setInterval与setTimeout就解决了我们这一个困难。至于想删除这一个时间控那就更简单了,直接clearInterval的setInterval的返回对象就可以了啊!
2.setTimeout 和 clearTimeout的属性和方法应用.做一个调用的累计功能
1 <form> 2 <input type="button" value="Start count!" id="counts"/> 3 <input type="text" id="txt"/> 4 <input type="button" value="Stop count!" id="stop"/> 5 </form> 6 <script type="text/javascript"> 7 var c = 0; 8 var t; 9 document.getElementById("counts").onclick = timeCount; 10 document.getElementById("stop").onclick = timeStop; 11 function timeCount(){ 12 document.getElementById("txt").value = c; 13 c+=1; 14 t = setTimeout("timeCount()",1000); 15 } 16 function timeStop(){ 17 clearTimeout(t); 18 } 19 </script>
说明:创建一个变量做为累计计算用,和一个setTimeout的返回对象名;分别获得counts和 stop的节点并分别绑定onclick事件赋予相应处理函数。函数timeCount得到id为txt的value等于累计变量c,记得在第一次运行时这是累计变量的初始值。调用setTimeout不断的累加。
3.open
1 <button id="opens">click i,new open</button> 2 <script type="text/javascript"> 3 document.getElementById("opens").onclick = opens; //为id等于opens的节点绑定一个onclick事作 4 function opens(){ 5 var left = "400"; //这是x 坐标 6 var top = "470"; //这是y 坐标 7 var x = (screen.width - left)/2; //屏幕的宽度减去窗口x坐标值 8 var y = (screen.height - top)/2; //屏幕的高度减去窗口y坐标值 9 open('close.html','jvascript自学','width=400,height=400,left='+x+',top='+y); 10 } 11 </script>
4.confirm的使用
1 <button id="confirms">你就来蹂躏我吧!</button> 2 <div id="confirscontent"></div> 3 <script type="text/javascript"> 4 document.getElementById("confirms").onclick = confirms; 5 function confirms(){ 6 var r = confirm("Press a button"); 7 if(r == true){ 8 document.getElementById("confirscontent").innerText = "You perssed OK!!"; 9 }else{ 10 document.getElementById("confirscontent").innerText = "You perssed Cancel!!"; 11 } 12 } 13 </script>
5.scroolBy 把内容指定多少像素滚动
<button id="scrol">哥们你挡着我的手机信号了.</button> <div style="height:2000px;width:100%"> <p>吃香焦得剥皮,"运动"时还得安全安全!!</p> </div> <script type="text/javascript"> document.getElementById("scrol").onclick = scrols; function scrols(){ window.scrollBy(200,200) } </script>
6.scrollTo 把内容滚动到指定像素。
<button id="scrolltos">不要讲我高傲,只是我不与一般人打交到.</button> <script type="text/javascript"> document.getElementById("scrolltos").onclick = scrolltos; function scrolltos(){ window.scrollTo(100,0); } </script>