JavaScript Window对象与用户交互

版权声明:ByRisonBoy https://blog.csdn.net/Rison_Li/article/details/82972242

前言:Window对象是打开浏览器窗口,可以控制窗口的大小和位置、窗口弹出框、打开和关闭窗口。控制窗口显示地址栏,工具栏。还可以控制是否重载网页、返回上一个或下一个文档。

1、警告对话框

window.alert(str);

代码片段:

<html>
    <body>
        <script type="text/javascript">
            function win(){
                window.alert("你好,我是一个警告框!");
            }
            win();
        </script>
    </body>
</html>

结果显示:

2、窗口打开和关闭

 window.open(url, "","");

代码片段:

<html>
    <body>
        <script type="text/javascript">
            function win(){
               window.open("https://blog.csdn.net/Rison_Li","","");
            }
            win();
        </script>
    </body>
</html>

显示结果:

打开一个new窗口:

window.open("https://blog.csdn.net/Rison_Li","new");

打开一个指定大小的窗口:

window.open("https://blog.csdn.net/Rison_Li","new","height = 100, width = 200");

打开一个带滚动条的窗口:

window.open("https://blog.csdn.net/Rison_Li","new","scrollbars,resizable");

关闭当前窗口:window.close();

3、询问回答框

window.confirm(str);

代码片段:

<html>
    <body>
        <script type="text/javascript">
            function win(){
               var test = window.confirm("是否要关闭浏览器?");
               if(test == true) window.close();
            }
            win();
        </script>
    </body>
</html>

显示结果:

4、窗口滚动

window.scrolly(x,y);

代码片段:

 <script type="text/javascript">
            var x = 0;
            function win(){
                    x++;
                    window.scroll(0,x);
                    clearTimeout(t);
                    var t = setTimeout("win()",10);
            }
            win();
        </script>

显示结果:

5、访问窗口历史

代码片段:

 <a href = "javascript:window.history.go(-1);">后退</a>
 <a href = "javascript:window.history.back(2);">前进</a>
 <a href = "javascript:window.history.go(window.historylength-1);">末尾</a>

6、窗口事件

代码片段:

<html>
    <body onfocus="a1();"  onblur="a2();">
           <script language="javascript">
                function a1(){
                    document.write("窗口获得焦点");
                }
                function a2(){
                    document.write("窗口失去焦点");
                }   
           </script>
    </body>
</html>

显示结果:

其他事件:

onload:文档载入时响应

onunload:文档未载入时响应

onresize:用户改变窗口大小响应

onerror:javascript错误时,触发错误处理事件

7、自动调整分辨率

代码片段:

<html>
    <body onload="size();">
           <script language="javascript">
                function size(){
                   window.resizeTo(screen.width - 100,screen.height - 100);
                }   
           </script>
    </body>
</html>

希望对你有帮助,学会window对象对窗口进行一些简单的控制。

猜你喜欢

转载自blog.csdn.net/Rison_Li/article/details/82972242
今日推荐