zoukankan      html  css  js  c++  java
  • JS之DOM编程

       为什么学dom编程

    1. 通过dom编程,我们可以写出各种网页游戏
    2. dom编程也是我们学习ajax技术的基础,所以我们必需掌握好dom编程。

       dom编程简介

       DOM=Document Object Model(文档对象模型),根据W3C DOM规范,DOM是HTML与XML的应用编程接口(API),DOM将整个页面映射为一个由层次节点组成的文件。

       js把浏览器,网页文档和网页文档中的html元素都用相应的内置对象来表示,这些对象与对象间的层次关系称为dom,针对网页(html,jsp,php,aspx,net)的dom就html dom,我们此处讲的就是html dom。

       关于使用js对xml文件的dom编程,我们这暂时不讲。到讲ajax的时候在给大家讲解。

       dom分为html dom与xml dom。

       可以借助数据库编程来讲清dom编程分类。

       DOM原理

       

       dom编程简介--dom对象

       前面说过,js把浏览器,网页文档和网页文档中的html元素都用相应的内置对象(看文档)来表示,这些对象与对象间的层次关系称为dom,针对网页(html,jsp,php,aspx,net)的dom就是html dom。我们这讲的就是html dom

       这里有几个特别重要的概念要给大家说清楚:

    1. 上面说的内置对象就是dom对象,准确的说是html dom对象。
    2. 因为目前讲的是html dom编程,所以提到的dom编程,dom对象都是说的html dom编程和html dom对象,请大家不要犯迷糊。
    3. dom编程时,会把html文档看做是一颗dom树。
    4. dom编程的核心就是各个dom对象。

       dom编程简介--html dom层次图

       html dom定义了访问和操作html文档的标准方法。

       html dom把html文档呈现为带有元素、属性和文本的树结构(节点树)

       

       下面举例说明:

       有如下html文档:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <input type="button" value="Node测试" onclick="test()" /><br>
        <table border="1px">
            <tr>
            <td></td>
            <td><input type="button" value="向上走" onclick="move(this)" /></td>
            <td></td>
            </tr>
            <tr>
            <td><input type="button" value="向左走" onclick="move(this)" /></td>
            <td></td>
            <td><input type="button" value="向右走" onclick="move(this)" /></td>
            </tr>
            <tr>
            <td></td>
            <td><input type="button" value="向下走" onclick="move(this)" /></td>
            <td></td>
            </tr>
        </table>
        <!--把乌龟放在div中-->
        <div id="wugui" style="position:absolute;left:100px;top:120px;">
            <img src="1.jpg" border="1px" alt="" />
        </div>
        <!--鸡放在div中-->
        <div id="cock" style="position:absolute;left:200px;top:200px;">
            <img src="2.jpg" border="1px" alt="" />
        </div>
    </body>
    </html>

       则dom树为:

       

       bom简介

       BOM(The Browser Object Model)--浏览器对象模型

       

       

       通过使用BOM,可移动窗口、更改状态栏文本。bom是w3c组织提出的,他建议所有的浏览器都应当遵循这样的设计规范,可以说bom和dom关系密切,相互影响,bom为纲,dom为目,我们可以简单的理解dom就是bom的具体实现。

       dom简介

    1. dom(document object model)文档对象模型,根据w3c dom规定,dom是html和xml的应用程序编程接口(api),dom将html或xml映射成由层次节点组成的模型,根据规范的严格层度,分为1,2,3级。
    2. dom的核心是提供了一套访问结构化文档的api,核心是对节点各种操作。

       

       dom对象简介

       js把浏览器,网页文档和网页文档中的html元素和相应的内置对象来表示,这些内置对象就是dom对象,编程人员通过访问dom对象,就可以实现对浏览器本身、网页文档、网页文档中元素的操作,从而控制浏览器和网页元素的行为和外观。

       常用的dom对象一览图

       

       这里,只列举了常用的dom对象。从上图可以看出:

       dom对象本身也有层次,比如document对象是window对象的一个成员属性,而body对象又是document对象的一个成员属性。

       而在前面说过,dom编程其实就是把网页文档看做是一棵树(html dom tree)(倒的),然后用相应的dom对象去访问网页文档,从而达到控制浏览器和网页的行为和外观。

       

       

       window对象

       

       window对象表示一个浏览器窗口或一个框架。在客户端javascript中,window对象是全局对象,要引用当前窗口根本不需要特殊的语法,可以把那个窗口的属性作为全局变量来用。在使用window对象的方法和属性的时候,可以不带window,比如:window.alert("李阿昀!");,可以直接写成alert("李阿昀!");

       讲解window对象常用的函数和属性,其它的参考http://www.w3school.com.cn/jsref/dom_obj_window.asp,还有很多可能需要在做项目的时候,才会接触。

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

       说明:如果用户点击确定按钮,则confirm()返回 true。如果点击取消按钮,则confirm()返回 false。如下例:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            function test() {
                var result = window.confirm("你要删除吗?");
                if(result) {
                    window.alert("删除");
                } else {
                    window.alert("放弃删除");
                }
            }
        </script>
    </head>
    <body>
        <input type="button" value="删除记录" onclick="test()" />
    </body>
    </html>
    setInterval() 按照指定的周期(以毫秒计)来调用函数或计算表达式
    clearInterval() 取消由 setInterval()设置的timeout

       说明:setInterval()方法会不停地调用函数,直到clearInterval()被调用或窗口被关闭。由setInterval()返回的ID值可用作clearInterval()方法的参数。

       记住:setInterval()函数会先等待再执行(如何让它先执行再等待?这是一个疑问。)

       案例1:需求每隔5秒钟弹出hello world!

       代码如下:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            function sayHello() {
                window.alert("hello, world!");
            }
            setInterval("sayHello()", 5000);
        </script>
    </head>
    <body>
        
    </body>
    </html>

       案例2:模拟一个时钟。

       代码如下:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            function showTime() {
                //在元素间的文本就是通过对象名.innerText设置的
                document.getElementById("mytime").innerText = new Date().toLocaleString();
            }
            setInterval("showTime()", 1000);
        </script>
    </head>
    <body>
        <span id="mytime"></span><br/>
    </body>
    </html>

       案例3:让静态图片动起来!(图片有点多,就不放上来了)

       代码如下:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            //让静态图片动起来
            var n = 1;
            function runChild() {
                //得到myimg对象
                //window.alert(myimg.src);
                var myimg = document.getElementById("myimg");
                myimg.src = ((n++ % 13)+1)+".jpg";
            }
            var myTimer = setInterval("runChild()", 1000);
        </script>
    </head>
    <body>
        <div>
            <img src="1.jpg" id="myimg" />
        </div>
    </body>
    </html>

       进一步,扩展要求:小人动10s就停止。

       代码如下:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            var count = 0;
            var n = 1;
            //让静态图片动起来
            function runChild() {
                count++;
                if(count == 11) {
                    //停止这个定时器
                    clearInterval(myTimer);
                }
                //得到myimg对象
                //window.alert(myimg.src);
                var myimg = document.getElementById("myimg");
                myimg.src = ((n++ % 13)+1)+".jpg";
            }
            var myTimer = setInterval("runChild()", 1000);
        </script>
    </head>
    <body>
        <div>
            <img src="1.jpg" id="myimg" />
        </div>
    </body>
    </html>
    setTimeout() 在指定的毫秒数后调用函数或计算表达式
    clearTimeout()  取消由setTimeout()方法设置的timeout

       说明:setTimeout()只执行code一次。如果要多次调用,请使用setInterval()或者让code自身再次调用setTimeout()。

       案例4:延时5秒弹出hello对话框。

       代码如下:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            //5秒后调用sayHello()
            function sayHello() {
                window.alert("hello");
            }
            setTimeout("sayHello()", 5000);
        </script>
    </head>
    <body>
    
    </body>
    </html>

       案例5:让静态图片动起来!动10s就停下,接着歇5秒再动,循环往复...

       代码如下:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            var count = 0;
            var n = 1;
            //让静态图片动起来
            function runChild() {
                count++;
                if(count == 11) {
                    //停止这个定时器
                    clearInterval(myTimer);
                    setTimeout("reRun()", 5000);//歇5秒
                    count = 0;
                }
                //得到myimg对象
                //window.alert(myimg.src);
                var myimg = document.getElementById("myimg");
                myimg.src = ((n++ % 13)+1)+".jpg";
            }
            //setInterval函数会先等待再执行(如何让它先执行再等待?)
            var myTimer = setInterval("runChild()", 1000);
    
            function reRun() {
                myTimer = setInterval("runChild()", 1000);
            }
        </script>
    </head>
    <body>
        <div>
            <img src="1.jpg" id="myimg" />
        </div>
    </body>
    </html>

       我觉得setTimeout()和setInterval()并不是那么简单的,上面的这些就是一些初步了解而已,希望自己以后能彻底能搞明白!

    moveTo() 把窗口的左上角移动到一个指定的坐标
    moveBy() 可相对窗口的当前坐标把它移动指定的像素

       如下示例:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            function test() {
                window.moveTo(100, 100);// 需在窗口化下才可看到演示
                var move = window.confirm("是否再次移动?");
                if(move) {
                    window.moveBy(100, 100);
                }
            }
        </script>
    </head>
    <body>
        <input type="button" value="移动" onclick="test()" />
    </body>
    </html>
    resizeTo() 把窗口大小调整为指定的宽度和高度
    resizeBy() 根据指定的像素来调整窗口的大小

       如下例:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            function test() {
                resizeBy(300,200);
            }
            function test2() {
                resizeTo(400,500);
            }
        </script>
    </head>
    <body>
        <input type="button" value="按像素调整窗口大小" onclick="test()" /><br/>
        <input type="button" value="指定窗口为宽400高500" onclick="test2()" />
    </body>
    </html>

       下面再讲一个open()函数的使用,可参考http://www.w3school.com.cn/jsref/met_win_open.asp#windowfeatures

       示例如下:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            function test() {
                window.open("newWindow.html","_blank","channelmode=yes,resizable=no,width=800,height=800,location=no");
            }
        </script>
    </head>
    <body>
        <input type="button" value="打开一个新窗口" onclick="test()" />
    </body>
    </html>
    opener属性 返回对创建该窗口的 Window 对象的引用

       opener属性非常有用,创建的窗口可以引用创建它的窗口所定义的属性和函数。

       例:opener父窗口和子窗口通信。(只在IE9中通过测试)

       父窗口(window.html):

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            var newWindow;
            function test2() {
                newWindow = window.open("newWindow.html","_blank","channelmode=yes,resizable=no,width=600,height=500,location=no");
            }
            function test3() {
                newWindow.document.getElementById("info").value = $("info2").value;
            }
            function $(id) {
                return document.getElementById(id);
            }
        </script>
    </head>
    <body>
        我是一个窗口
        <input type="button" value="打开新窗口" onclick="test2()" />
        <span id="myspan">消息</span><br/>
        <input type="text" value="" id="info2" /><input type="button" value="通知给子窗口" onclick="test3()" />
    </body>
    </html>

       子窗口(newWindow.html):

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            function notify() {
                var val = document.getElementById("info").value;
                opener.document.getElementById("myspan").innerText = val;
            }
        </script>
    </head>
    <body>
        我是新窗口
        <input type="text" value="" id="info" /><input type="button" value="通知给父窗口" onclick="notify()" />
    </body>
    </html>

       在掌握window对象一些常用方法后,我们来看几个案例。

       一个js版本的用户登录系统,当用户输入admin密码是123456就跳到第二页面,4秒后,自动跳转到第三个页面。

       login.html:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            function checkUser() {
                if($("uname").value == "admin" && $("pwd").value == "123456") {
                    //window.alert("ok");
                    return true;
                } else {
                    //window.alert("no ok");
                    $("uname").value = "";
                    $("pwd").value = "";
                    return false;
                }
            }
             function $(id) {
                 return document.getElementById(id);
             }
        </script>
    </head>
    <body>
        <form action="ok.html">
            账号:<input type="text" id="uname" /><br/>
            密码:<input type="password" id="pwd" /><br/>
            <input type="submit" onclick="return checkUser()" value="登录" />
        </form>
    </body>
    </html>

       过渡页面(ok.html):

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            function changeSec() {
                $("myspan").innerText = parseInt($("myspan").innerText) - 1;
            }
            var myTimer = setInterval("changeSec()", 1000);
            function tiao() {
                clearInterval(myTimer);
                window.open("manage.html", "_self");
            }
            setTimeout("tiao()", 5000); //等价于setTimeout("javascript:window.open('manage.html', '_self')", 5000);
            function $(id) {
                return document.getElementById(id);
            }
        </script>
    </head>
    <body>
        登录成功!<span id="myspan">5</span>秒后自动跳转到管理页面
    </body>
    </html>

       manage.html:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        管理界面
    </body>
    </html>

       status的使用(可以控制状态栏信息),IE9和Chrome均没通过测试:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script language="javascript" type="text/javascript">
        <!--
            var space_num=0;
            var dir=1;
            function myScroll(){
                var space_my="";
                space_num=space_num+1*dir;
                if(space_num>50||space_num<0){
                    dir=dir*-1;
                }
                for(var i=0;i<space_num;i++){
                    space_my=space_my+" ";
                }
                window.status=space_my+"世界你好!";
            }
            function startIt(){
                setInterval("myScroll()",100);
            }
        //-->
    </script>
    </head>
    <body onload="startIt()">
        
    </body>
    </html>

       history对象

       

       history对象:Contains information about the URLs visited by the client,即:该对象包含客户端访问过的URL信息。

       从dom层次图看,history是window对象的成员属性,但实际history是由js runtime engine自动创建的,所以你也可以认为history就是一个js对象。

       history对象常用的函数和属性可参考http://www.w3school.com.cn/jsref/dom_obj_history.asp

       例,

       historyA.html:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <a href="historyB.html">goto historyB</a>
    </body>
    </html>

       historyB.html:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            function goback() {
                window.alert(history.length);
                history.back();//等价于history.go(-1);
            }
        </script>
    </head>
    <body>
        <!-- 不只是input可以有onclick事件 -->
        <a href="#" onclick="goback()">返回上一级页面</a>
    </body>
    </html>

       location对象

       

       location对象:Contains information about the current URL。即:该对象包含客户端当前URL信息。

       从dom层次图看,location是window对象的成员属性,但实际location也是由js runtime engine自动创建的,所以你也可以认为location就是一个js对象。

       location属性和方法可参考http://www.w3school.com.cn/jsref/dom_obj_location.asp

       例,

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            function test() {
                location.reload();//等同刷新页面
                //window.alert(location.href+" || "+location.hostname+" || "+location.port);
            }
        </script>
    </head>
    <body>
        12345677
        <input type="button" value="刷新页面" onclick="test()" />
    </body>
    </html>

       

       navigator对象

       

       navigator对象:Contains information about the browser,即:该对象包含当前浏览器的各信息。

       从dom层次图看,navigator是window对象的成员属性,但实际navigator也是由js runtime engine自动创建的,所以你也可以认为navigator就是一个js对象。

       navigator对象常用的函数和属性可参考http://www.w3school.com.cn/jsref/dom_obj_navigator.asp

       例,

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            document.write("<p>Name: ");
            document.write(navigator.appName + "</p>"+navigator.platform+" "+navigator.systemLanguage);
        </script>
    </head>
    <body>
        
    </body>
    </html>

       

       screen对象

       

       screen对象:Contains information about the client's screen and rendering capabilities,即:该对象包含有关客户机显示屏幕的信息。

       从dom层次图看,screen是window对象的成员属性,但实际screen也是由js runtime engine自动创建的,所以你也可以认为screen就是一个js对象。

       screen对象常用的属性可参考http://www.w3school.com.cn/jsref/dom_obj_screen.asp

       例,

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            document.write(screen.width+" "+screen.height+" "+screen.availHeight);
        </script>
    </head>
    <body>
        
    </body>
    </html>

       event对象

       

       event对象代表事件的状态,比如事件在其中发生的元素、键盘按键的状态、鼠标的位置、鼠标按钮的状态,事件通常与函数结合使用。

       从dom对象层次图看,event对象是window对象的属性,其实在其它的dom对象中都存在event事件(一种event对象就代表一类事件),理解这一点非常重要!

       事件驱动编程

       所谓事件驱动,简单地说就是你点什么按钮(即产生什么事件),电脑执行什么操作(用什么函数)。当然事件不仅限于用户的操作,当对象处于某种状态时,可以获得消息通知,然后对这个消息感兴趣的程序就可以执行。

       事件驱动编程的几个核心对象

       事件源:谁发出事件通知,发出消息就是事件主体。

       事件名称:发出什么样的通知的名称,比如鼠标到我头上了,我被别人点了一下。

       事件响应函数:谁对这个事件感兴趣,当这个事件发生时要执行什么样的操作。

       事件对象:一般来说,当事件发生时,会产生一个描述该事件的具体对象,包括具体的参数一起发给响应函数,好让他们通过事件对象来了解事件更加详细的信息。

       特别注意:前面已详细讲解了event事件,这里就不在详细阐述了。

       如何绑定事件监听

    1. 直接在某个html控件上指定
    2. getElementById("xxx")获取控件后,再绑定
    3. 通过addEventListener()或者是attachEvent()来绑定
    4. 一个事件可以有多个事件监听者(函数)

       W3C DOM标准:

    [Object].addEventListener("name_of_event",fnHandler,bCapture);
    [Object].removeEventListener("name_of_event",fnHandler,bCapture);

       IE中独有的事件监听方法:

    [Object].attachEvent("name_of_event_handler",fnHandler);
    [Object].detachEvent("name_of_event_handler",fnHandler);

       ①通过getElementById("")获取控件后绑定事件

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            function test() {
                alert("hello");
            }
        </script>
    </head>
    <body>
        <input id="but" type="button" value="测试" />
        <script type="text/javascript">
            document.getElementById("but").onclick = test;
        </script>
    </body>
    </html>

       此绑定比较类似于:

    function Person() {
    
    }
    var p = new Person();
    p.fun1 = function() {
    
    }

       ②在IE下通过attachEvent绑定和detachEvent解除绑定

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            function test() {
                window.alert("你投了一次票");
                //解除事件绑定
                document.getElementById("but").detachEvent("onclick", test);
            }
        </script>
    </head>
    <body>
        <input id="but" type="button" value="投票" />
        <script type="text/javascript">
            document.getElementById("but").attachEvent("onclick", test);
        </script>
    </body>
    </html>

       如何获取事件对象

       dom会将事件对象通过参数传递给响应函数(事件监听函数),而ie则可以直接通过window.event来获取事件对象。

       非IE浏览器

       DOM中获取事件对象:DOM中要求event是传给事件响应函数的第一个参数。

    oDiv.onclick=function(){
        var oEvent=arguments[0];
        //oEvent即为事件对象
    }

       或

    oDiv.onclick=function(oEvent){
        //参数oEvent即为事件对象
    }

       IE浏览器

       IE中的Event对象-window.event

    oDiv.onclick=function(){
        var oEvent=window.event;
        //oEvent就是事件对象
    }

       这里特别强调一点,并不是所有的html元素都有相同的event事件(对象),这个请大家在做项目的时候特别注意,比如提交按钮有onsubmit事件,但是输入框就没有的,具体参考js帮助文档。

       案例:要求用户在一个输入框中输入一个数,如果不是数字,则给出提示。

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript">
            function test(e) {
                //用户每按下一个键,就去判断是不是一个数
                if(e.keyCode < 48 || e.keyCode > 57) {
                    window.alert("您输入的不是数");
                    //window.event.returnValue = false;
                    return false;
                }
            }
        </script>
    </head>
    <body>
        <input type="text" onkeypress="return test(event)" id="text1" />
    </body>
    </html>

        

     

  • 相关阅读:
    IDEA使用总结1-Github下载代码和上传代码到Git
    Mysql-安装指南
    Dubbo安装及其实战1
    分布式设计(学习内容目录--后端架构师)
    elasticsearch安装指导(new)
    浅谈TCP/IP(new 常见面试问题)
    浅谈常用的设计模式(new)
    浅谈Elasicsearch
    浅谈数据库分库分表(new)
    JAVA 电子书下载地址
  • 原文地址:https://www.cnblogs.com/yerenyuan/p/5397261.html
Copyright © 2011-2022 走看看