JS进阶(一)BOM
BOM:browser object model ,浏览器提供我们开发者在js用于操作浏览器的对象。
没有DOM核心哦,所以过一下即可,而且简简单单的。
一. window对象
window是js中最大的对象,整个浏览器窗口出现的所有东西都是Windows对象的内容
1.三个弹窗方法:
- alert() 或 window.alert() 警告
- confirm() 或 window.confirm() 有一个返回值
- prompt() 或 window.prompt() 有一个输入框,返回值是输入的内容
var res = window.confirm("是否继续?")
console.log(res) // bool值,取消是false,确认是true
var res2 = window.prompt("请输入一个数字")
console.log(res2) // 返回值是输入的内容
2.定时方法
setInterval()
setTimeout()
setInterval() 方法会不停地调用函数,知道clearInterval()被调用或者窗口被关闭。由setInterval() 返回的id值可用作clearInterval()方法的参数。而setTimeout() 是在指定的毫秒数后调用code一次。
定时器语法:
// 设置循环定时器 var ID = window.setInterval(code,millisec) //每隔millisec毫秒执行一次code // 取消循环定时器 window.clearInterval(ID) // 设置单次定时器 var ID = window.setTimeout(code,millisec) // 每millisec毫秒后执行一次code // 取消单次定时器 window.clearTimeout(ID)
简单一点的使用:
// 延迟性的操作
window.setTimeout(function(){
console.log('mjj');
},0)
console.log('xiongdada');
var num = 0;
var timer = null;
timer = setInterval(function(){
num++;
if (num > 5) {
clearInterval(timer);
return;
}
console.log('num:'+ num);
},1000);
定时器案例:
代码里有一个点我不明白://这里为什么不用setTime(),调用函数不用加括号吗,那上面那句为什么加括号
只要是需要执行的都要加括号,因此事件里的要加括号。是这样吗?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>定时器案例</title>
<script>
function setTime(){
var now = new Date();
var now_str = now.toLocaleString(); //toLocaleString() 根据本地时间把Date对象转换为字符串
console.log(now_str)
// 通过document获取标签
var element = document.getElementById("time_input");
console.log(element);
element.value = now_str; //这是属性不是方法,是给属性赋值
}
var ID;
function start() {
// 仅第一次点击可以计时,防止开好几个定时器,无法结束
if(id==undefined){
setTime();
ID = window.setInterval(setTime, 1000) //这里为什么不用setTime(),调用函数不用加括号吗,那上面那句为什么加括号
}
}
function end(){
clearInterval(ID);
ID = undefined;//这一步是为了保证结束后可以重新开始
}
</script>
</head>
<body>
<input type="text" value="" id="time_input"> <button onclick="start()">start</button><button onclick="end()">end</button>
</body>
</html>
3. 打开关闭浏览器
window.open("Bootstrap中文网 (bootcss.com)","_blank","width=800px,height=500px,top=200px,left=200px"); //_blank打开一个新的浏览器窗口
window.close();
二、Location对象(地址栏对象)
// url:协议:域名端口/路径?参数
// 所有这些信息都可以通过location获取到
console.log(location);
// url完整信息
console.log(location.href);
// 域名和端口host,只有域名是hostname,只有端口是port
console.log(location.host);
console.log(location.hostname);
console.log(location.port);
// 路径
console.log(location.pathname);
// 参数
console.log(location.search);
两个比较简单的事件:刷新页面、页面跳转
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script>
function gooooo(){
// 两种方法
location.href = "https://www.cnblogs.com/firstdata/p/5580011.html"; // 其实js赋值很多都是=号唉,给属性赋值就是=
location.assign("www.baidu.com")// 方法,给方法传参
}
function fresh(){
location.reload();
}
</script>
</head>
<body>
<button onclick="gooooo()">页面跳转</button>
<button onclick="fresh()">页面刷新</button>
</body>
</html>
三、本地存储对象
使用存储对象的过程中,对象数据会根据域名端口进行保存的,所以js不能获取当前页面以外其他域名端口保存到本地的数据。也就是说,我们存储对象获取数据只能是自己当前端口或者域名下曾经设置过的数据,一旦端口或者域名改变,则无法获取原来的数据。
浙公网安备 33010602011771号