window对象不但充当全局作用域,而且表示浏览器窗口。
window对象有innerWidth和innerHeight属性,可以获取浏览器窗口的内部宽度和高度。
例如:
<script>
//可以调整浏览器窗口大小试试:
console.log('window inner size: ' + window.innerWidth + ' x ' + window.innerHeight);
</script>
window打开各类窗口
1)弹出一个警告框alert()
<script>
window.alert('这是一个警告框')
</script>
2)弹出一个确认框confirm()
<script>
if (confirm("确定要离开吗")){
console.log('退出系统...');
}else{
console.log('欢迎您回来...');
}
</script>
3)弹出一个提示框prompt()
<script>
let name = '';
name = prompt("请输入您的尊姓大名:")
console.log("欢迎您:"+name);
</script>
4)打开一个新窗口open()
<script>
let width = 500;
let high = 300;
let l=(window.innerWidth-width)/2;
let t=(window.innerHeight-high)/2;
//弹出一个垂直水平居中的窗口
window.open('https://www.baidu.com', null, 'width='+width+',height='+high+', top='+t+',left='+l+',toolbar=no,menubar=no,location=no,status=yes');
</script>
注意:大部分浏览器都会禁用此弹窗模式,需要设置解禁。
Javascript并不支持多线程运算,所以经常使用setTimeout和setInterval方法模拟线程
定时器常用方法 - setTimeout 在指定的毫秒数后调用函数或计算表达式,延迟执行,仅仅执行一次。 - clearTimeout 取消由setTimeout方法设置的定时任务 - setInterval 按照指定的周期来调用函数或计算表达式,每隔一定周期执行,反复执行。 - clearInterval 取消由setInterval方法设置的定时任务
例如:使用setTimeout和setInterval方法模拟电子时钟效果 1)使用setTimeout。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="text" id="myclock" value="" readonly/>
<input type="button" value="停止" onclick="stopclock();"/>
<input type="button" value="开始" onclick="startclock();"/>
<script>
let mytimer;
function show(){
let d = new Date();
let myclock = d.toLocaleString();
document.getElementById("myclock").value=myclock;
mytimer = setTimeout("show()",1000); //递归调用
}
function stopclock(){
//停止一个定时器对象。
clearTimeout(mytimer);
}
function startclock(){
show();
}
function myclock(){
show();
}
window.onload = myclock;
</script>
</body>
</html>
运行效果:
2)使用setInterval
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="text" id="myclock" value="" readonly/>
<input type="button" value="停止" onclick="stopclock();"/>
<input type="button" value="开始" onclick="startclock();"/>
<script>
let mytimer;
function show(){
let d = new Date();
let myclock = d.toLocaleString();
document.getElementById("myclock").value=myclock;
}
function stopclock(){
//停止一个定时器对象。
clearInterval(mytimer);
}
function startclock(){
mytimer = setInterval("show()",1000);
}
function myclock(){
show();
mytimer = setInterval("show()",1000);
}
window.onload = myclock;
</script>
</body>
</html>
运行效果:
