浏览器对象模型使得JavaScript能够与浏览器对话,比如,告诉浏览器需要调到一个新的窗口。
JavaScript与浏览器对话主要依靠的就是window对象,window对象表示web浏览器的一个窗口或者窗体,window对象有一些特有的属性,比如location属性表示当前浏览器所在窗口的URL,即网址。
本实训主要讲解window对象的主要属性,以及建立在这些属性之上的JavaScript和浏览器的对话方式。通过学习本实训,你将体会到JavaScript如何操作浏览器,这是JavaScript强大之处的提现。
一
定时器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p onclick="handleTimer()">set timer then undo</p>
<script>
var timeId;
function timerTask() {
console.log("this is timer task");
}
function handleTimer() {
//请在此处编写代码
/********** Begin **********/
//定时器 Id=window.setTimeout(a,b) b毫秒后执行a
//window.clearTimeout(Id)
var timeId=window.setTimeout(timerTask(),2000);
/********** End **********/
}
</script>
</body>
</html>
二
循环定时器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p onclick="task1()">this is task onea</p>
<p onclick="task2()">this is task two</p>
<p onclick="removeTask1()">try to remove task one</p>
<script>
var timeId1;
var timeId2;
function timerTask1() {
console.log("timerTask1!");
}
function timerTask2() {
console.log("timerTask2!");
}
function task1() {
timeId1 = window.setInterval(timerTask1,2000);
}
function task2() {
timeId2 = window.setInterval(timerTask2,1500);
}
function removeTask1() {
//请在此处编写代码
/********** Begin **********/
//循环定时器 window.setInterval(a,b) 每隔b毫秒执行a任务
window.clearInterval(timeId1);
/********** End **********/
}
</script>
</body>
</html>
三
location对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p onclick="openNew()">Click me to new page!</p>
<script>
function openNew() {
//请在此处编写代码
/********** Begin **********/
//window.location 当前窗口页面的信息 location.href 当前页面的地址
var loc=window.location;
console.log(loc.host);
loc.href="https://www.educoder.net/forums/categories/all?order=newest";
/********** End **********/
}
</script>
</body>
</html>
四
对话框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p onclick="inputName()">Click to input name!</p>
<script>
function inputName() {
var result;
//请在此处编写代码
/********** Begin **********/
//对话框
//一 警告框 window.alert()
//二 确认框 window.confirm()
//三 输入框 window.prompt(a,b) 参数a为提示内容 参数b为默认输入
result=window.prompt("your name","Xiao Ming");
if(result==null){
console.log("name cannot be null");
}
/********** End **********/
}
</script>
</body>
</html>
五
窗口
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p onclick="openNewWindow()">open new window</p>
<script>
var myWindow;
function openNewWindow() {
//请在此处编写代码
/********** Begin **********/
//窗口
//打开窗口 window.open(url,name,specs,replace)
//url 文档的地址
//name 窗口名
//specs 打开窗口的尺寸
//replace 控制新的窗口在阅览器的阅览历史里面如何显示
//关闭窗口 result=window.open(url,name,specs,replace)
//result.close();
var myWindow=window.open("Demo.html","window_name");
/********** End **********/
}
</script>
</body>
</html>