BOM
- DOM文档对象模型
- BOM浏览器对象模型
BOM通过js对浏览器的相关操作
BOM为我们定义了一些对象,这些对象完成浏览器的操作
BOM对象:
window:全局对象,直接访问(代表整个浏览器的窗口,同时window也是网页中的全局对象)
navigator:代表浏览器当前的信息,通过该对象可以识别不同的浏览器
location:代表当前浏览器的地址栏,可以获取或更改地址栏信息
history:表示浏览器的浏览历史记录,由于隐私原因,只能操作向前或向后的翻页记录(上一步)
history:表示用户的当前屏幕的相关信息(注意:指的是电脑屏幕,不是浏览器)
navigator对象
console.log(navigator.userAgent);
var us = navigator.userAgent;
if (/chrome/i.test(us)) {
console.log('谷歌浏览器');
}else if(/Firefox/i.test(us)){
console.log('火狐浏览器');
}else if(/compatible/i.test(us)){
console.log('IE浏览器');
}else if(/.NET/i.test(us)){
console.log('IE11浏览器');
}
history对象
<script>
location = "http://www.baidu.com";
</script>
location对象
- history.back() 后退
- history.forword() 前进
- history.go(n) 跳转指定步数(正数:向前跳转n步,负数:回退n步)
定时器
- setInterval()
- clearInterval()
window.onload = function () {
var h1 = document.querySelector("h1");
var t = 0;
var add = function () {
// console.log("---");
h1.innerText = parseInt(h1.innerText) + 1;
if (h1.innerText == 10) {
clearInterval(t);
}
};
// 使用定时器循环调用指定的方法
t = setInterval(add, 100);
};
</script>
图片自动切换
<script>
window.onload = function () {
var y = 0;
// 获取按钮
var start = document.querySelectorAll("button")[0];
var end = document.querySelectorAll("button")[1];
var img = document.querySelector("img");
var timer = 0;
// 保存图片路径的数组
var imgs = [];
for (var i = 0; i < 5; i++) {
imgs[i] = "./img/0" + (i + 1) + ".jpg";
}
// 开始
start.onclick = () => {
// 保证图片循环
timer = setInterval(() => {
y++;
img.src = imgs[y - 1];
if (y == 5) {
y = 1;
}
}, 1000);
};
// 结束
end.onclick = () => {
clearInterval(timer);
};
};
</script>
键盘移动(改)
<script>
window.onload = function () {
var div = document.querySelector("div");
// 定义速度
var speed = 10;
// 定义键盘的uncode编码
var dir;
// 键盘按下
setInterval(() => {
switch (dir) {
case 38: // 上
div.style.top = div.offsetTop - speed + "px";
break;
case 40: // 下
div.style.top = div.offsetTop + speed + "px";
break;
case 37: // 左
div.style.left = div.offsetLeft + speed + "px";
break;
case 39: // 上
div.style.left = div.offsetLeft - speed + "px";
break;
default:
break;
}
}, 1000);
// 获取键盘的uncode编码
document.onkeydown = (e) => {
e = e || window.event;
dir = e.keyCode;
};
};
</script>