《中级前端1.9》JavaScript浏览器对象——window,计时器,History,Location,Screen,cookie
JS浏览器对象-window对象
<button id="btn" onclick="btnClicked()">按钮</button> <script> //其实就是window.document.write,只是一般都可以省略 document.write("宽度:" + window.innerWidth + ",高度:" + window.innerHeight); function btnClicked() { window.open("DOMObj.html", "我是窗口名", "height=200,widht=200,top=100,left=100"); window.close(); } </script>
JS浏览器对象-计时器
setInterval("函数", 间隔毫秒) 是自带循环的。
setTimeout("函数", 间隔毫秒) 是执行一次,如需循环,需要放在函数中递归调用函数。
下面例子包括了setInterval()和引用传递参数对象(http://www.cnblogs.com/woodk/p/5128302.html)
<script> var mytime = self.setInterval(function() { getTime(); }, 1000); //alert("ok"); function getTime() { var timer = new Date(); var t = { h: timer.getHours(), m: timer.getMinutes(), s: timer.getSeconds() } //将时间对象t,传入函数checkTime(),直接在checkTime()中改变对象中的值。 //而无需再去接收返回值再赋值 checkTime(t); document.getElementById("timer").innerHTML = t.h + ":" + t.m + ":" + t.s; } function checkTime(i) { if (i.h < 10) { i.h = "0" + i.h; } if (i.m < 10) { i.m = "0" + i.m; } if (i.s < 10) { i.s = "0" + i.s; } } </script>
JS浏览器对象-History对象
<a href="javascript:history.go(-1);">返回</a> <a href="javascript:history.back();">返回</a> <a href="javascript:history.forward();">前进</a>
JS浏览器对象-Location对象
<script> window.location = "http://www.baidu.com"; document.write(window.location.hostname); document.write(window.location.pathname); document.write(window.location.port); document.write(window.location.protocol); document.write(window.location.href); //assign加载新页面,并且不能通过history.back()返回。 //document.write(window.location.assign("http://www.baidu.com")); </script>
JS浏览器对象-Screen对象
<script> document.write("可用高度:" + screen.availHeight + ",可用宽度:" + screen.availWidth); document.write("高度:" + screen.height + ",宽度:" + screen.width); </script>
显示器的宽高。
JS浏览器对象-cookie
cookie 用来识别用户。 具体看:http://www.w3school.com.cn/js/js_cookies.asp
下面是一个欢迎用户cookie的程序:
1 <html> 2 3 <head> 4 <script type="text/javascript">function getCookie(c_name) { 5 if (document.cookie.length > 0) { 6 c_start = document.cookie.indexOf(c_name + "=") 7 if (c_start != -1) { 8 c_start = c_start + c_name.length + 1 9 c_end = document.cookie.indexOf(";", c_start) 10 if (c_end == -1) c_end = document.cookie.length 11 return unescape(document.cookie.substring(c_start, c_end)) 12 } 13 } 14 return "" 15 } 16 17 function setCookie(c_name, value, expiredays) { 18 var exdate = new Date() 19 exdate.setDate(exdate.getDate() + expiredays) 20 document.cookie = c_name + "=" + escape(value) + 21 ((expiredays == null) ? "" : "; expires=" + exdate.toGMTString()) 22 } 23 24 function checkCookie() { 25 username = getCookie('username') 26 if (username != null && username != "") { 27 alert('Welcome again ' + username + '!') 28 } else { 29 username = prompt('Please enter your name:', "") 30 if (username != null && username != "") { 31 setCookie('username', username, 365) 32 } 33 } 34 }</script> 35 </head> 36 37 <body onLoad="checkCookie()"> 38 </body> 39 40 </html>
->