BOM对象
BOM(浏览器对象模型),可以对浏览器窗口进行访问和操作。使用 BOM,开发者可以移动窗口、改变状态栏中的文本以及执行其他与页面内容不直接相关的动作。
使 JavaScript 有能力与浏览器“对话”。
所有浏览器都支持 window 对象。
功能上讲: 控制浏览器窗口的.
使用上讲: window对象不需要创建对象,直接使用即可.
window 对象方法
alert() 显示带有一段消息和一个确认按钮的警告框。
confirm() 显示带有一段消息以及确认按钮和取消按钮的对话框。
prompt() 显示可提示用户输入的对话框
open() 打开一个新的浏览器窗口或查找一个已命名的窗口。
close() 关闭浏览器窗口。
setInterval() 按照指定的周期(以毫秒计)来调用函数或计算表达式。
clearInterval() 取消由 setInterval() 设置的 timeout。
setTimeout() 在指定的毫秒数后调用函数或计算表达式。 用于轮播图
clearTimeout() 取消由 setTimeout() 方法设置的 timeout。
scrollTo() 把内容滚动到指定的坐标。
代码示例:
<script> //window 方法 alert("hello"); window.alert("window hello"); res=confirm("确认"); res1=window.confirm("window 确认"); document.write(res," windows ",res1); res2=prompt("hello..."); document.write('<br>',"res2"); open("http://www.chenxm.cc/"); setInterval(f,1000); var i=0; function f(){ document.write(i+=1); } </script>
跑马灯js代码示例:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="text" id="id1" onclick="begin()"> <button onclick="end()">停止</button> <br> <input type="text" id="id2" onclick="begin1()"> <button onclick="end1()">停止</button> </body> <script> function showTime(){ var current_time=new Date().toLocaleString(); var ele=document.getElementById("id1"); ele.value=current_time } var clock1; function begin(){ showTime(); clock1=setInterval(showTime,1000); } function end(){ clearInterval(clock1) } </script> // 解决方法 <script> function showTime1(){ var current_time1=new Date().toLocaleString(); var ele1=document.getElementById("id2"); ele1.value=current_time1 } var clock2; function begin1(){ if (clock2==undefined){ showTime(); clock2=setInterval(showTime1,1000); } } function end1(){ clearInterval(clock2); clock2=undefined; } </script> </html>
分析:
出现bug原因,是因为第一种方案,用户点击输入框第一次,触发clock1变量,当用户点击第二次,clock1变量又被触发,但是之前clock1变量被顶替了,没有变量名,所以用户点击多次输入框后,再点击停止,无法让时间停止运行。
setTimeout clearTimeout
var ID = setTimeout(abc,2000); // 只调用一次对应函数. clearTimeout(ID); function abc(){ alert('aaa'); }
History 对象(比较少用)
History 对象包含用户(在浏览器窗口中)访问过的 URL。
History 对象是 window 对象的一部分,可通过 window.history 属性对其进行访问。
History 对象方法
back() 加载 history 列表中的前一个 URL。
forward() 加载 history 列表中的下一个 URL。
go() 加载 history 列表中的某个具体页面。
<script> <button onclick=" history.forward()">>>></button> <button onclick="history.back("-1")">back</button> <button onclick="history.go("1")">back</button> </script>
Location 对象(比较少用)
Location 对象包含有关当前 URL 的信息。
Location 对象是 Window 对象的一个部分,可通过 window.location 属性来访问。
location方法:
location.assign(URL) 跳转到指定页面 可以后退
location.reload() 刷新
location.replace(newURL) //注意与assign的区别 不可以后退