js window对象常用内容

window对象表示的是浏览器的窗口。如果文档包含框架(frame 或 iframe 标签),浏览器会为 HTML 文档创建一个 window 对象,并为每个框架创建一个额外的 window 对象。

没有多个框架,在一个框架中,window为一个,所以window可以省略书写。

它有很多属性和方法。

Navigator   获取浏览器的信息

Screen     获取屏幕的信息

History    包含用户在浏览器窗口中访问过的 URL。

这里介绍window中的两个计时器,setInterval 与setTimeout

这两个计时器是有区别的,setInterval是指达到一定时间段,不断重复进行执行。

而setTimeout是指在达到一定时间后,执行一次。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/javascript" />
    <title>testjs</title>


    <style type="text/css">
    </style>
</head>
<body>
    <div id="div1">asdad</div>
    <button id="stop">时间停止</button>
    <button id="stop1">取消sayhello</button>
    <script type="text/javascript">
        function time() {
            var date = new Date();
            document.getElementById("div1").innerText = date;
        }
        var gettime = setInterval("time()", 500);      //每500毫秒执行一次time函数,所以页面时间不断刷新
        document.getElementById("stop").onclick = (function () {       //给按钮添加事件,点击的时候停止刷新时间
            clearInterval(gettime); 
        })

        function sayhello() {                                
            alert("hello");
        }
        var hello = setTimeout("sayhello()", 5000);                //5秒钟之后执行sayhello函数
        document.getElementById("stop1").onclick = function () {     //给按钮添加事件,点击后5秒后不在执行函数
            clearTimeout(hello);
        }

    </script>

</body>

window对象还有最常用的的对话框。

alert()   显示带有一段消息和一个确认按钮的警告框。

comfirm()   显示带有一段消息以及确认按钮和取消按钮的对话框。

prompt()   显示可提示用户输入的对话框。

 1 <html>
 2 <head>
 3 <script type="text/javascript">
 4 function disp_prompt()      
 5   {
 6   var name=prompt("Please enter your name","")  //第一个参数问提示信息,第二个参数为输入的值。  返回输入的值
 7   if (name!=null && name!="")
 8     {
 9     document.write("Hello " + name + "!")
10     }
11   }
12 function disp_confirm()     
13   {
14   var r=confirm("Press a button")       //参数为提示信息,点击确认返回true,取消返回false
15   if (r==true)
16     {
17     document.write("You pressed OK!")    
18     }
19   else
20     {
21     document.write("You pressed Cancel!")
22     }
23   }
24 function display_alert()    //警告信息框,弹出提示信息,只有确认按钮,无返回信息
25   {
26   alert("I am an alert box!!")
27   }
28 </script>
29 </head>
30 <body>
31 
32 <input type="button" onclick="display_alert()"
33 value="Display alert box" />
34 
35 </body>
36 </html>
原文地址:https://www.cnblogs.com/joe2014/p/3822445.html