一、window对象
1.所有浏览器都支持window对象,它表示浏览器窗口;
2.所有JS全局对象、函数以及变量均自动成为window对象的成员;
3.全局变量为其属性;
var index=0;
console.log(window.index);
4.全局函数为其方法;
var index = 0;
window.showName();
function showName() {
console.log(window.index);
}
5.HTML DOM的document也是window对象的属性之一:window.document.getElementById(“header”);
与document.getElementById(“header”);相同
二、window尺寸
写法一:
console.log(window.screen.width); //1600 浏览器总宽
console.log(window.screen.availWidth); //1600 浏览器实际宽
console.log(window.screen.height); //900 浏览器总高
console.log(window.screen.availHeight); //860 浏览器实际高
写法二:
document.documentElement.clientWidth; //获取浏览器可视区域的宽,调试器不算
document.documentElement.clientHeight; //获取可视区域的高,调试器不算
写法三(不建议使用body,需要清margin,不清则需要计算):
console.log(document.body.clientWidth); //body的实际宽,比浏览器可视区域的宽少16px,因为浏览器默认外间距margin为8px
console.log(document.body.clientHeight); //0,body里内容目前为0,body的实际高
写法四:
console.log(window.innerWidth); //浏览器窗口的内部宽度
console.log(window.innerHeight); //浏览器窗口的内部高度
三、其他window方法
1.window.open();
打开新窗口
注:window.open(url,name,feature,replace);
若name使用名字已经存在,则不会创建一个新窗口,而是会返回对已经存在的窗口的引用;否则,创建一个新窗口
2.window.close();
关闭当前窗口
var btn = document.getElementById("btn");
btn.onclick = function () {
window.close();
}
3.window.moveTo();
移动当前窗口 被限制
4.window.resizeTo();
语法格式:window.resizeTo(width,height);
width:必需,想要调整到的窗口的宽度,以像素计;
height:可选,想要调整到的窗口的高度,以像素计
window.resizeTo(200,200); //不能直接使用,必须调整打开的窗口大小
var win = window.open("txt.html", "", "width=100,height=100");
win.resizeTo(300, 300);
四、方法
alert(); //提示框
confirm(“请输入”); //带确认,取消按钮的提示框
prompt(“请输入”,“2”); //带输入文本的提示框
五、window对象里的计时器
1.setTimeout():延迟一段时间,执行一次
var count = 1;
setTimeout(function () {
count++;
console.log(count);
}, 1000); //延迟1s,执行里面的函数一次
例:用setTimeout()实现循环计时器:用函数的递归
var count = 0;
var time;
showtime();
function showtime() {
count++;
console.log(count);
time = setTimeout("showtime()", 1000);
}
//停止加开启计时器
var btnstop = document.getElementById("btnstop");
var btnstart = document.getElementById("btnstart");
btnstop.onclick = function () {
clearTimeout(time);
}
btnstart.onclick = function () {
time = setTimeout("showtime()", 1000);
}
2.setInterval():延迟一段时间,循环执行
var time;
var count = 0;
showtime();
function showtime() {
time = setInterval(function () {
count++;
console.log(count);
}, 1000);
}
var btnstop = document.getElementById("btnstop");
var btnstart = document.getElementById("btnstart");
btnstop.onclick = function () {
clearInterval(time);
};
btnstart.onclick = function () {
showtime();
}