Head first javascript(三)

setTimeout, 单位是毫秒

setTimeout ( time code, timer delay );

eg:

setTimeout("alert('wake up!')", 100000);

The document object表示网页代码本身

修改用户窗口(不是整个浏览器)的大小,可以用body.clientWidth, body.clientHeight,这样可以适应不同窗口的大小,如果要动态根据当前窗口的大小来改变大小,可以用onresize触发。

function resize(){
    ...
}
...
<body onload = "resize();" onresize = "resize();">

javascript在关闭浏览器的时候会把所有的变量都清除,所以每次重开网页都会重新运行整个脚本。如果需要一些变量可以记录下来重复使用,可以在关闭网页时使用cookie把变量记录下来下一次使用

cookie

name = Jack
Expires 11/11/2014

cookie使用的使用都要声明它的Expires结束时间,到了结束时间就会自动删除,如果没有声明结束时间则视为跟普通变量一样,在关闭浏览器的时候清除。cookies之间用;分隔。 cookie的使用函数示例:

function writeCookie(name, value, days) {
	// By default, there is no expiration so the cookie is temporary
	var expires = "";

	// Specifying a number of days makes the cookie persistent
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		expires = "; expires=" + date.toGMTString();
	}

	// Set the cookie to the name, value, and expiration date
	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
	// Find the specified cookie and return its value
	var searchName = name + "=";
	var cookies = document.cookie.split(';');
	for (var i = 0; i < cookies.length; i++) {
		var c = cookies[i];
		while (c.charAt(0) == ' ') //去除开头多余的空格
			c = c.substring(1, c.length);
		if (c.indexOf(searchName) == 0)
			return c.substring(searchName.length, c.length);
	}
	return null; //找不到结果返回null
}

function eraseCookie(name) {
	// Erase the specified cookie
	writeCookie(name, "", -1);
}

可以把这些函数放到.js后缀的文件里


navigator.cookieEnabled可以查看当前是否可以使用cookie

原文地址:https://www.cnblogs.com/jolin123/p/3930604.html