zoukankan      html  css  js  c++  java
  • 从零开始学习前端JAVASCRIPT — 6、JavaScript基础DOM

    1:DOM(Document  Object  Model)的概念和作用

    document对象是DOM核心对象:对html中的内容,属性,样式进行操作。

    节点树中节点之间的关系:父子,兄弟。


    2:DOM常用属性

    title:返回或设置当前文档的标题。

    console.log(document.title);   //打印网页标题—读
    document.title="hello world";  //更改网页标题—写

       all:返回所有元素的集合。

     console.log(document.all);//输出网页的所有元素
    

    forms:返回对文档中所有form对象的引用。 

    console.log(document.forms['formone'])

    通过集合来访问相应的对象:

    1.通过下标的形式。

    2.通过name形式。


     3:DOM查询方法

    1.getElementById(id):返回拥有指定id的(第一个)对象的引用。

    console.log(document.getElementById('box'))
    

    2.getElementsByTagName(tagName):返回有指定标签名的对象集合。

    console.log(document.getElementsByTagName('div'));
    

    注:上面两个方法没有兼容性问题。

    3.getElementsByName(name):返回带有指定name指定名称的对象的集合。有兼容性问题。

    console.log(document.getElementsByName('form1').length);
    

    在IE9及其以下,如果该对象的标准属性包含有name,(比如说input,在input中name是input的默认属性,所以可以正常使用,但是在div中name并不是div的默认属性,所以不能正常显示),那么可以正确的使用。否则不可以使用。在火狐中,该方法可以适用于任何情况。

    结论: getElementsByName(name)主要是适用于表单。

    4.write:输出内容到页面。(注:网页加载完成后进行输出,则覆盖整个网页,使用时需注意)

    document.write('下雪啦!');
    

    5.getElementsByClassName():返回带有指定className指定名称的对象的集合。有兼容性问题,适用于火狐浏览器,在IE浏览器中不可用(IE8及以下不可用)。

    console.log(document.getElementsByClassName('pink'))
    

    封装获取className值的DOM节点的兼容性的函数。

    // 通过class名获取元素集合
    function byClassName(sClassName) {
    	if(document.getElementsByClassName) {
    		return document.getElementsByClassName(sClassName);
    	} else {
    		// 获取所有的元素
    		var allTags = document.getElementsByTagName('*');
    		var result = [];
    		for(var i = 0; i < allTags.length; i++) {
    			if(allTags[i].className == sClassName) {
    				result.push(allTags[i]);
    			}
    		}
    		return result;
    	}
    }
    console.log(byClassName('pink').length)

     4:操作内容

    1.innerHTML:用来设置或获取对象起始和结束标签内(例如div框架,它只会获取div里面的内容,而不会获取div)的内容(识别html标签) 。

    console.log(oBox.innerHTML);//输出内部的标签及文字
     oBox.innerHTML = '<i>我是测试数据</i>';  //文字倾斜,不显示标签
    

     2.innerText:用来设置或获取对象起始和结束标签内的内容 (只是获取文字内容)(适用于IE,最新版火狐已支持)。

      textContent用来设置或获取对象起始和结束标签内的内容 (只是获取文字内容)(适用于火狐,IE8及其以下不支持)。

    console.log(oBox.innerText);  //只输出文字
    
    oBox.innerText = '<i>我是测试数据</i>'; //文字不倾斜,标签当文字输出
    

    3.outerHTML  用来设置或获取包括本对象在内的起始和结束标签内(例如div框架,不仅会获取div里面的内容,也会获取div自身的内容)的内容(识别html标签) 。

    4.outerText  用来设置或获取包括本对象在内的起始和结束标签内的内容(只是获取文字内容)(火狐不支持)。

    // 写入的区别
     oBox.outerHTML = '<i>测试数据</i>';
     oBox.outerText = '<i>测试数据</i>';
    //outerHTML 替换该标签插入html标签i文字发生倾斜
    //outerText  替换该标签插入文字不发生倾斜标签当文字处理

     5:操作属性

    1.直接操作

          对象.属性。   // 获取属性。某些属性有兼容性问题,例如name(如果不是标签特有的属性,在chrome/firfox访问不到,在IE8及其以下浏览器能获取的到)。

          对象.属性=值  // 设置、添加属性(属性值)。

    //通过属性的方式操作读写
    oBox.id = 'snow';
    oBox.age = '24';
    console.log(oBox.id);
    console.log(oBox.age);
    

    2.通过方法

          getAttribute(“属性”)。  

    console.log(oBox.getAttribute('id'));
    console.log(oBox.getAttribute('age'));
    

         setAttribute(“属性”,“值”)。 

    Box.setAttribute('id', 'snow');
    oBox.setAttribute('age', 24);
    

        removeAttribute(“属性”)。    

    // 删除属性
    oBox.removeAttribute('color');

    6:操作样式

    1.行内样式

         对象.style.属性       // 获取样式属性

    // 只能读取行内样式
    console.log(oBox.style.width)
    console.log(oBox.style.height)
    console.log(oBox.style.color)
    console.log(oBox.style.backgroundColor)
    

         对象.style.属性=值  // 设置、添加样式属性。

    // 只能设置行内样式
    oBox.style.width = '400px';
    oBox.style.backgroundColor = 'blue';
    

         注: 遇到属性是“-”链接的,要将“-”去掉,后面的单词的首字母大写,采用驼峰式命名的方法进行书写。

       2.行内样式和css层叠样式通用的方式

    对象.currentStyle.属性                IE   用来获得实际的样式属性。

    getComputedStyle((对象,null).属性)   火狐  用来获得实际的样式属性。

    注:只能获取不能设置。

    封装获取样式通用方式:

    // 获取元素样式值
    function getStyle(obj, attr) {
    	if(obj.currentStyle) {
    		return obj.currentStyle[attr];
    	} else {
    		return getComputedStyle(obj, false)[attr];
    	}
    }
    
    console.log(getStyle(oBox, 'width'));

     7:DOM增删改

    一:创建节点(注释和文档节点一般不需要创建)

        1:创建元素节点

            document.createElement("元素标签名");

        2:创建属性节点

            var oAttr = document.createAttribute(“属性名”);(不常用)

               oAttr.value = "attr-name";

               oDiv.setAttributeNode(oAttr);

            对象.属性=属性值;(常用)

        3:创建文本节点

            对象.innerHTML = "";

            var oText = document.createTextNode(“文本”);  // 文本中的HTML标签实体化

               oDiv.appendChild(oText);

    二:追加到页面当中

        父对象.appendChild(newNode)  // 插入到父对象最后。

        父对象.insertBefore(newNode, existsNode)   // 插入到什么对象之前。

    三:修改(替换)节点

        父对象.replaceChild(newNode,existsNode);  // 前面的替换后面的

    四:删除节点

        父对象.removeChild(oldNode);

         如果确定要删除节点,最好也清空内存  对象=null;

    五:表格操作

         table.tBodies[0].rows[0].cells[0].innerHTML;

         var oNewRow = table.insertRow(“行位置”);

       oNewRow.insertCell(“列位置”);

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>动态操作表格</title>
        <script type="text/javascript">
            //封装$函数方便后续的使用
            function $(id) {
                return document.getElementById(id)
            }
            window.onload=function() {
                var tBody=($("testtable")).tBodies[0];
                var deleteBtn=document.getElementsByClassName('adelete');
                console.log(deleteBtn)
                binddelete();
                function binddelete(){
                    for(var i = 0; i < deleteBtn.length; i++) {
                        deleteBtn[i].onclick=function() {
                            tBody.removeChild(this.parentNode.parentNode);
                        }
                    }
                }
                ($("addCreateTable")).onclick=function() {
                    var orderNum=parseInt(tBody.rows[tBody.rows.length-1].cells[0].innerText) + 1;
                    if (!orderNum) {orderNum=1;}
                    //以上代码不要注释
                    //通过创建元素的方式动态创建表格(可注释的区域查看另一种方法)
            /*        var newtd1=document.createElement('td');
                    var newtd2=document.createElement('td');
                    var newtd3=document.createElement('td');
                    var newtd4=document.createElement('td');
                    newtd1.innerHTML=orderNum;
                    newtd2.innerHTML="location.hash";
                    newtd3.innerHTML="获取锚点";
                    newtd4.innerHTML="<a class='adelete' href='javascript:;'>删除</a>";
                    var newtr=document.createElement('tr');
                    newtr.appendChild(newtd1);
                    newtr.appendChild(newtd2);
                    newtr.appendChild(newtd3);
                    newtr.appendChild(newtd4);
                    tBody.appendChild(newtr);*/
                    //通过表格方法动态创建表格(可注释的区域查看另一种方法)
                    var newRow=tBody.insertRow(tBody.rows.length);
                    var newCell=newRow.insertCell(tBody.lastChild.cells.length);
                    newCell.innerHTML=orderNum;
                    var newCell=newRow.insertCell(tBody.lastChild.cells.length);
                    newCell.innerHTML=2;
                    var newCell=newRow.insertCell(tBody.lastChild.cells.length);
                    newCell.innerHTML=3;
                    var newCell=newRow.insertCell(tBody.lastChild.cells.length);
                    newCell.innerHTML="<a class='adelete' href='javascript:;'>删除</a>";
                    binddelete();
                };
            }
        </script>
    </head>
    <body>
        <table id = "testtable">
            <tr>
                <td>序号</td>
                <td>属性</td>
                <td>属性值</td>
                <td>操作</td>
            </tr>
            <tr>
                <td colspan="4" style="text-align: center;">
                    <a href="javascript:;" id="addCreateTable">
                        增加一行三列
                    </a>
                </td>
            </tr>
            <tr>
                <td>1</td>
                <td>location.href</td>
                <td>指向网页的链接地址</td>
                <td><a class="adelete" href="javascript:;">删除</a></td>
            </tr>
            <tr>
                <td>2</td>
                <td>location.search</td>
                <td>指向网页的链接地址</td>
                <td><a class="adelete" href="javascript:;">删除</a></td>
            </tr>
        </table>
    </body>
    </html>
    动态创建表格的两种方式
            // 创建LI标签
    	var oLi = document.createElement('li');
    	oLi.innerHTML = '这是第' + Math.round(Math.random() * 1000 + 10) + '条新闻';
    	// 将新的标签追加到元素的末尾
    	 oList.appendChild(oLi);
    	// 将新的元素放到第一个位置
    	oList.insertBefore(oLi, aLi[0]);
    	// 替换节点
    	oList.replaceChild(oLi, aLi[0]);
    	// 删除节点
    	 oList.removeChild(aLi[0]);
    	// 创建属性节点
            oList.className = 'aaa';
    	oList.sex = '男';
    	var oHeight = document.createAttribute('height');
    	oHeight .value = '180cm';
    	oList.setAttributeNode(oHeight );
    	// 创建文本节点
    	var oText = document.createTextNode('新创建的文本节点');
    	oList.appendChild(oText);
    	// 表格的操作
    	var oTable = document.getElementById('table');
    	// 获取tBody
    	var tBody = oTable.tBodies[0];
    	// 获取tr
    	 var oTr = tBody.rows[2];
    	// 获取td
    	 var oTd = oTr.cells[1];
    	// 读取
    	 console.log(oTd.innerHTML);
    	// 修改
    	oTd.innerHTML = 'second';
    	// 添加新的一行
    	// var oNewTr = tBody.insertRow(5);
    	//  创建四列
    	 var oNewTd = oNewTr.insertCell(0);
    	 oNewTd.innerHTML = 5;
    	 var oNewTd = oNewTr.insertCell(1);
    	 oNewTd.innerHTML = '你猜五';
    	 var oNewTd = oNewTr.insertCell(2);
    	 oNewTd.innerHTML = 0;
    	 var oNewTd = oNewTr.insertCell(3);
    	 oNewTd.innerHTML = '女';
    	// 删除一行
    	var oDeleteTr = tBody.rows[tBody.rows.length - 1];
    	tBody.removeChild(oDeleteTr);                
    

    8:DOM节点简介

    根据 DOM规定,HTML 文档中的每个成分都是一个节点。

    DOM 是这样规定的:

        整个文档是一个文档节点。

        每个 HTML 标签是一个元素节点。

        包含在 HTML 元素中的文本是文本节点。

        每一个 HTML 属性是一个属性节点。

    注释属于注释节点。


    9:如何获取DOM节点

    1:旧的获取节点引用方式。

    getElementById()

    getElementsByTagName()

    getElementsByName()

    缺点:浪费内存,逻辑性不强。


     10:通过节点的关系属性来获得节点的引用。

    对象.parentNode  获得父节点的引用。

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="boxone" class="boxone">
            boxone
        </div>
        <div id="boxtwo" class="boxtwo">
            boxtwo
        </div>
    </body>
    <script type="text/javascript">
        //封装$函数
        function $(id) {
            return document.getElementById(id);
        }
        //获取父节点的引用
        console.log($("boxone").parentNode)
    </script>
    </html>
    parentNode

     

    对象.childNodes  获得子节点的集合,包括空白节点。IE7/8不包含空文本节点,但IE7包含首个注释节点(前面没有元素节点),IE8包含所有的注释节点。

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="box" class="box">
            <div id="boxone" class="boxone">
                boxone
            </div>
            <div id="boxtwo" class="boxtwo">
                boxtwo
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*封装$函数*/
        function $(id) {
            return document.getElementById(id);
        }
        /*获取父节点的引用*/
        // console.log($("boxone").parentNode)
        /*获取子节点的集合(获取集合基本上都是负数)*/
        console.log($("box").childNodes)
    
    </script>
    </html>
    childNodes

    对象.children    获得子节点的集合,不包含空白节点。但IE7包含首个注释节点(前面没有元素节点),IE8包含所有的注释节点。

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="box" class="box">
            <div id="boxone" class="boxone">
                boxone
            </div>
            <div id="boxtwo" class="boxtwo">
                boxtwo
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*封装$函数*/
        function $(id) {
            return document.getElementById(id);
        }
        /*获取父节点的引用*/
        // console.log($("boxone").parentNode)
        /*获取子节点的集合*/
        console.log($("box").childNodes) //包含空白节点
        console.log($("box").children)   //不包含空白节点
    
    </script>
    </html>
    children

     

    对象.firstChild  获得第一个子节点。(IE7/8非空白节点,可能是注释节点)

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="box" class="box">
            <div id="boxone" class="boxone">
                boxone
            </div>
            <div id="boxtwo" class="boxtwo">
                boxtwo
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*封装$函数*/
        function $(id) {
            return document.getElementById(id);
        }
        /*获取父节点的引用*/
        // console.log($("boxone").parentNode)
        /*获取子节点的集合*/
        // console.log($("box").childNodes) //包含空白节点
        // console.log($("box").children)   //不包含空白节点
        console.log($("box").firstChild)    //获取第一个空白子节点
    
    </script>
    </html>
    firstChild

     

    对象.firstElementChild  获得第一个非空白的子节点。(IE7/8不支持)

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="box" class="box">
            <div id="boxone" class="boxone">
                boxone
            </div>
            <div id="boxtwo" class="boxtwo">
                boxtwo
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*封装$函数*/
        function $(id) {
            return document.getElementById(id);
        }
        /*获取父节点的引用*/
        // console.log($("boxone").parentNode)
        /*获取子节点的集合*/
        // console.log($("box").childNodes) //包含空白节点
        // console.log($("box").children)   //不包含空白节点
        console.log($("box").firstChild)    //获取第一个空白子节点
        console.log($("box").firstElementChild) //获取第一个非空白子节点
    </script>
    </html>
    firstElementChild

     

    对象.lastChild   获得最后一个子节点。(IE7最后一个元素节点,IE8最后一个非空白节点,可能是注释节点)

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="box" class="box">
            <div id="boxone" class="boxone">
                boxone
            </div>
            <div id="boxtwo" class="boxtwo">
                boxtwo
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*封装$函数*/
        function $(id) {
            return document.getElementById(id);
        }
        /*获取父节点的引用*/
        // console.log($("boxone").parentNode)
        /*获取子节点的集合*/
        // console.log($("box").childNodes) //包含空白节点
        // console.log($("box").children)   //不包含空白节点
        // console.log($("box").firstChild)    //获取第一个空白子节点
        // console.log($("box").firstElementChild) //获取第一个非空白子节点
        console.log($("box").lastChild)     //获取最后一个空白子节点
    </script>
    </html>
    lastChild

     

    对象.lastElementChild   获得最后一个非空白的子节点。(IE7/8不支持)

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="box" class="box">
            <div id="boxone" class="boxone">
                boxone
            </div>
            <div id="boxtwo" class="boxtwo">
                boxtwo
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*封装$函数*/
        function $(id) {
            return document.getElementById(id);
        }
        /*获取父节点的引用*/
        // console.log($("boxone").parentNode)
        /*获取子节点的集合*/
        // console.log($("box").childNodes) //包含空白节点
        // console.log($("box").children)   //不包含空白节点
        // console.log($("box").firstChild)    //获取第一个空白子节点
        // console.log($("box").firstElementChild) //获取第一个非空白子节点
        console.log($("box").lastChild)     //获取最后一个空白子节点
        console.log($("box").lastElementChild)   //获取最后一个非空白子节点
    </script>
    </html>
    lastElementChild

      

    对象.nextSibling 获得下个兄弟节点的引用。 (包括空白节点和注释。IE7/8包括注释节点,不包括空白节点。)

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="box" class="box">
            <div id="boxone" class="boxone">
                boxone
            </div>
            <div id="boxtwo" class="boxtwo">
                boxtwo
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*封装$函数*/
        function $(id) {
            return document.getElementById(id);
        }
        /*获取父节点的引用*/
        // console.log($("boxone").parentNode)
        /*获取子节点的集合*/
        // console.log($("box").childNodes) //包含空白节点
        // console.log($("box").children)   //不包含空白节点
        // console.log($("box").firstChild)    //获取第一个空白子节点
        // console.log($("box").firstElementChild) //获取第一个非空白子节点
        // console.log($("box").lastChild)     //获取最后一个空白子节点
        // console.log($("box").lastElementChild)   //获取最后一个非空白子节点
        console.log($("box").nextSibling)     //获取下一个空白子节点
    </script>
    </html>
    nextSibling

     

    对象.nextElementSibling 获得下个兄弟节点的引用。 (IE7/8不支持)

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="box" class="box">
            <div id="boxone" class="boxone">
                boxone
            </div>
            <div id="boxtwo" class="boxtwo">
                boxtwo
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*封装$函数*/
        function $(id) {
            return document.getElementById(id);
        }
        /*获取父节点的引用*/
        // console.log($("boxone").parentNode)
        /*获取子节点的集合*/
        // console.log($("box").childNodes) //包含空白节点
        // console.log($("box").children)   //不包含空白节点
        // console.log($("box").firstChild)    //获取第一个空白子节点
        // console.log($("box").firstElementChild) //获取第一个非空白子节点
        // console.log($("box").lastChild)     //获取最后一个空白子节点
        // console.log($("box").lastElementChild)   //获取最后一个非空白子节点
        console.log($("boxone").nextSibling)     //获取下一个空白子节点
        console.log($("boxone").nextElementSibling)     //获取下一个空白子节点
    </script>
    </html>
    nextElementSibling

      

    对象.previousSibling 获得上个兄弟节点的引用。(包括空白节点和注释。 IE7/8包括注释节点,不包括空白节点。)

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="box" class="box">
            <div id="boxone" class="boxone">
                boxone
            </div>
            <div id="boxtwo" class="boxtwo">
                boxtwo
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*封装$函数*/
        function $(id) {
            return document.getElementById(id);
        }
        /*获取父节点的引用*/
        // console.log($("boxone").parentNode)
        /*获取子节点的集合*/
        // console.log($("box").childNodes) //包含空白节点
        // console.log($("box").children)   //不包含空白节点
        // console.log($("box").firstChild)    //获取第一个空白子节点
        // console.log($("box").firstElementChild) //获取第一个非空白子节点
        // console.log($("box").lastChild)     //获取最后一个空白子节点
        // console.log($("box").lastElementChild)   //获取最后一个非空白子节点
        // console.log($("boxone").nextSibling)     //获取下一个空白子节点
        // console.log($("boxone").nextElementSibling)     //获取下一个空白子节点
        console.log($("boxtwo").previousSibling)     //获取上一个空白子节点
    </script>
    </html>
    previousSilbling

      

    对象.previousElementSibling 获得上个兄弟节点的引用。(IE7/8不支持)

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="box" class="box">
            <div id="boxone" class="boxone">
                boxone
            </div>
            <div id="boxtwo" class="boxtwo">
                boxtwo
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*封装$函数*/
        function $(id) {
            return document.getElementById(id);
        }
        /*获取父节点的引用*/
        // console.log($("boxone").parentNode)
        /*获取子节点的集合*/
        // console.log($("box").childNodes) //包含空白节点
        // console.log($("box").children)   //不包含空白节点
        // console.log($("box").firstChild)    //获取第一个空白子节点
        // console.log($("box").firstElementChild) //获取第一个非空白子节点
        // console.log($("box").lastChild)     //获取最后一个空白子节点
        // console.log($("box").lastElementChild)   //获取最后一个非空白子节点
        // console.log($("boxone").nextSibling)     //获取下一个空白子节点
        // console.log($("boxone").nextElementSibling)     //获取下一个空白子节点
        console.log($("boxtwo").previousSibling)     //获取上一个空白子节点
        console.log($("boxtwo").previousElementSibling) //获取上一个空白子节点
    </script>
    </html>
    prviousSibling

      

      缺点:兼容性不好。


    11:节点其它属性

    ownerDocument:获取该节点的文档根节点,相当于 document。

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="box" class="box">
            <div id="boxone" class="boxone">
                boxone
            </div>
            <div id="boxtwo" class="boxtwo">
                boxtwo
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*封装$函数*/
        function $(id) {
            return document.getElementById(id);
        }
        /*获取该节点的文档根节点*/
        console.log($("box").ownerDocument);
    </script>
    </html>
    ownerDocument

     

    attributes:获取当前元素节点的所有属性节点集合(IE7下不正常)。

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="box" class="box">
            <div id="boxone" class="boxone">
                boxone
            </div>
            <div id="boxtwo" class="boxtwo">
                boxtwo
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*封装$函数*/
        function $(id) {
            return document.getElementById(id);
        }
        /*获取该节点的文档根节点*/
        // console.log($("box").ownerDocument);
        /*获取当前节点的所有属性集合*/
        console.log($("box").attributes);
    </script>
    </html>
    attributes

       tagName:获取元素节点的标签名。

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="box" class="box">
            <div id="boxone" class="boxone">
                boxone
            </div>
            <div id="boxtwo" class="boxtwo">
                boxtwo
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*封装$函数*/
        function $(id) {
            return document.getElementById(id);
        }
        /*获取该节点的文档根节点*/
        // console.log($("box").ownerDocument);
        /*获取当前节点的所有属性集合*/
        // console.log($("box").attributes);
        /*获取当前节点的标签名*/
        console.log($("box").tagName)  //注意标签名都是大写
    </script>
    </html>
    tagName

        

    id:元素节点的ID名称。

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="box" class="box">
            <div id="boxone" class="boxone">
                boxone
            </div>
            <div id="boxtwo" class="boxtwo">
                boxtwo
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*封装$函数*/
        function $(id) {
            return document.getElementById(id);
        }
        /*获取该节点的文档根节点*/
        // console.log($("box").ownerDocument);
        /*获取当前节点的所有属性集合*/
        // console.log($("box").attributes);
        /*获取当前节点的标签名*/
        // console.log($("box").tagName)  //注意标签名都是大写
        console.log($("box").id)
    </script>
    </html>
    id

      

    title:元素节点的title属性值(鼠标悬停时提示)。

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="box" class="box" title="外层盒子">
            <div id="boxone" class="boxone">
                boxone
            </div>
            <div id="boxtwo" class="boxtwo">
                boxtwo
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*封装$函数*/
        function $(id) {
            return document.getElementById(id);
        }
        /*获取该节点的文档根节点*/
        // console.log($("box").ownerDocument);
        /*获取当前节点的所有属性集合*/
        // console.log($("box").attributes);
        /*获取当前节点的标签名*/
        // console.log($("box").tagName)  //注意标签名都是大写
        /*获取当前节点的id值*/
        // console.log($("box").id)
        console.log($("box").title)
    </script>
    </html>
    title

     

    className:元素节点的类名(不可以使用class)。

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="box" class="box boxcss" title="外层盒子">
            <div id="boxone" class="boxone">
                boxone
            </div>
            <div id="boxtwo" class="boxtwo">
                boxtwo
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*封装$函数*/
        function $(id) {
            return document.getElementById(id);
        }
        /*获取该节点的文档根节点*/
        // console.log($("box").ownerDocument);
        /*获取当前节点的所有属性集合*/
        // console.log($("box").attributes);
        /*获取当前节点的标签名*/
        // console.log($("box").tagName)  //注意标签名都是大写
        /*获取当前节点的id值*/
        // console.log($("box").id)
        /*获取当前节点的提示信息title*/
        // console.log($("box").title)
        /*获取当前节点的引用外部、内部样式的名称*/
        console.log($("box").className)
    </script>
    </html>
    View Code

     

    扩展 :

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>dom介绍</title>
    </head>
    <body>
        <div id="box" class="box boxcss" title="外层盒子">
            <div id="boxone" class="boxone">
                boxone
            </div>
            <div id="boxtwo" class="boxtwo">
                boxtwo
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*封装$函数*/
        function $(id) {
            return document.getElementById(id);
        }
        /*获取该节点的文档根节点*/
        // console.log($("box").ownerDocument);
        /*获取当前节点的所有属性集合*/
        // console.log($("box").attributes);
        /*获取当前节点的标签名*/
        // console.log($("box").tagName)  //注意标签名都是大写
        /*获取当前节点的id值*/
        // console.log($("box").id)
        /*获取当前节点的提示信息title*/
        // console.log($("box").title)
        /*获取当前节点的引用外部、内部样式的名称*/
        // console.log($("box").className)
        /*————————————————————扩展——————————————————*/
        /*获取当前节点的引用外部、内部样式的名称列表*/
        console.dir($("box").classList)
        //增加外部、内部样式名称
        $("box").classList.add('c')
        //移除外部、内部样式名称
        $("box").classList.remove('b')
        //是否包含外部、内部样式名称
        console.log($("box").classList.contains('b'))
    </script>
    </html>
    扩展

    12:节点信息(属性)    

       节点类型(nodeType(数值))  节点名字(nodeName)  节点值(nodeVale)
    元素节点   1 标签名 null
    属性节点   2 属性名  属性值 
    文本节点  3 #text  文本 
    注释节点  8 #comment  注释的文字 
    文档节点  9 #document  null 

    13:创建文档碎片

    语法:var oFragment = document.createDocumentFragment();

    //方式一:普通方式
    var oList = document.querySelector('#list'); console.time('边创建边输出10000个LI执行的时间') for(var i = 1; i<= 10000; i++) { var oLi = document.createElement('li'); oLi.innerHTML = '这是第' + i + '个LI'; oList.appendChild(oLi); } console.time('边创建边输出10000个LI执行的时间') //方式二:创建文档碎片 var oFragment = document.createDocumentFragment(); console.timeEnd('创建10000个文档碎片LI执行的时间') for(var i = 1; i <= 10000; i++) { var oLi = document.createElement('li'); oLi.innerHTML = '这是第' + i + '个LI'; oFragment.appendChild(oLi); } oList.appendChild(oFragment); console.timeEnd('创建10000个文档碎片LI执行的时间') //普通方式边创建边输出 //创建文档碎片,创建放到容器,创建完成后输出

       经过测试,在ie,firefox下性能明显得以提高。


     14:节点计算属性

    1:offsetParent:获取元素的最近的具有定位属性(absolute或者relative)的父级元素。如果都没有则返回body。

    2:offsetLeft:获取元素相对具有定位属性的父级元素的左侧偏移距离。(子元素的marginLeft + left + 父元素的paddingLeft)

    3:offsetTop:获取元素相对就有定位属性的父级元素的顶部偏移距离。(子元素的marginTop + top + 父元素的paddingTop)

    4:scrollLeft/scrollTop:滚动条最顶端和窗口中可见内容的最顶端之间的距离。

    6:clientWidth/clientHeight:元素视窗宽度/高度。

    5:offsetWidth/offsetHeight:元素实际宽度/高度。

    6:scrollWidth/scrollHeight:获取对象的滚动宽度/高度。

     实时消息窗口滚动案例:

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>节点计算属性实际应用demo</title>
        <style type="text/css">
            *{
                padding:0;
                margin: 0;
            }
            html,body{
                height: 100%;
                position: relative;
            }
            .box{
                position: absolute;
                left: 0;
                top: 0;
                right: 0;
                bottom: 0;
                 60%;
                height: 250px;
                margin: auto;
                background: #f3f3f3;
                padding: 20px;
            }
            .innerbox{
                height: 200px;
                 100%;
                overflow: auto;
                border: 1px solid blue;
                border-radius: 10px;
            }
            .innerbox p{
                text-indent: 16px;
                line-height: 30px;
            }
            .region{
                text-align: right;
            }
            .box input{
                padding: 10px;
                background: blue;
                border: 1px solid black;
                letter-spacing: 8px;
                outline: none;
                border-radius: 5px;
                margin-top: 20px;
            }
        </style>
    </head>
    <body>
        <div class="box">
            <div id="innerBox" class="innerbox">
                
            </div>
            <div class="region">
                <input id="btnsubmit" type="submit" value="增加内容">            
            </div>
        </div>
        <script type="text/javascript">
            var inner=document.getElementById('innerBox')
            var btnSubmit=document.getElementById('btnsubmit')
            btnSubmit.onclick=function() {
                var newp=document.createElement("p");
                newp.innerHTML="我是一行<br/>";
                inner.appendChild(newp);
                //实现滚动条一直至于底部,一直展示更新的实时消息
                inner.scrollTop=inner.scrollHeight;
            }
        </script>
    </body>
    </html>
    节点计算属性的应用

    15:获取FORM表单

    一:通过直接定位的方式来获取

    document.getElementById();

    document.getElementsByName();

    document.getElementsByTagName();

    二:通过集合的方式来获取引用

    1.通过下标的形式

    document.forms[下标]

    2.通过name形式

    document.forms["name"]    document.forms.name

    三:通过name直接获取(只适用于表单)

    document.name


    16:获取FORM表单元素

    一:通过直接定位的方式来获取

    //前面已经讲过此种方式的用法(不再做实例)

    document.getElementById();

    document.getElementsByName();

    document.getElementsByTagName();

    二:通过集合来获取

    表单对象.elements     // 获得表单里面所有元素的集合

    表单对象.elements[下标]

    表单对象.elements["name"]

    表单对象.elements.name

    三:直接通过name的形式

    表单对象.name         // name指的是元素的name 

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>获取表达元素</title>
        <script type="text/javascript">
            window.onload=function() {
            var oForm = document.register;
            // 获取FORM表单中的元素
            console.log(oForm.elements);//获取表达元素集合
            console.log(oForm.elements['account']);//通过元素名称的方式访问
            console.log(oForm.elements[0]);//通过元素在表单的下标的方式访问
            console.log(oForm.elements.account);//通过对象访问.方式访问
            //以上都是通过表单集合的方式访问表达元素
            console.log(oForm.account)//直接通过name(元素的name)的方式访问
        }
        </script>
    </head>
    <body>
        <button id="btn">提交表单</button>
        <form action="" name="register">
            <div>账号:<input type="text" name="account" value="请输入账号!"></div>
            <div>密码:<input type="password" name="password"></div>
            <div>性别:<input type="radio" name="sex" value="boy" checked>男<input type="radio" name="sex" value="girl">女<input type="radio" name="sex" value="unknown">未知</div>
            <div>
                爱好:<input type="checkbox" name="hobby" value="basketball" checked>篮球<input type="checkbox" name="hobby" value="football" checked>足球<input type="checkbox" name="hobby" value="pingpang">乒乓球
            </div>
            <div>家乡:<select name="city">
                <option value="1">西安市</option>
                <option value="2" selected>咸阳市</option>
                <option value="3">宝鸡市</option>
                <option value="4">渭南市</option>
                <option value="5">铜川市</option>
            </select></div>
            <div>
                座右铭:<textarea name="" id="" cols="30" rows="10"></textarea>
            </div>
            <input type="submit" value="注册">
        </form>
    </body>
    </html>
    通过集合获取表达元素

    17:表单元素共同的属性和方法

    一:获取表单元素的值

    表单元素对象.value   // 获取或是设置值

    二:属性

    disabled   // 获取或设置表单控件是否禁用 true false

    form       // 指向包含本元素的表单的引用。(通过表单中元素找到相应的表单)

    三:方法   表单元素是否获得焦点

    blur()   // 失去焦点

    focus()  // 获得焦点

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>获取表达元素</title>
        <script type="text/javascript">
            window.onload=function() {
            var oForm = document.register;
            // 获取FORM表单中的元素
            /*console.log(oForm.elements);//获取表达元素集合
            console.log(oForm.elements['account']);//通过元素名称的方式访问
            console.log(oForm.elements[0]);//通过元素在表单的下标的方式访问
            console.log(oForm.elements.account);//通过对象访问.方式访问
            //以上都是通过表单集合的方式访问表达元素
            console.log(oForm.account)//直接通过name(元素的name)的方式访问*/
    
            console.log(oForm.city.value);//获取下拉框的选中值
            oForm.account.disabled = true;//账户按钮不可用,值:false可用
            console.log(oForm.account.form);//获取表单元素的所引用的表单
            //为看效果加延时器和改变样式
            setTimeout(function() {        
                oForm.password.style.border="2px solid red";
                oForm.password.style.textIndent="16px";
                oForm.password.style.outline="none";
                oForm.password.focus()
                //focus表单元素获取焦点的方法,效果同标签属性autofocus
            },2000)    
            setTimeout(function() {
                oForm.password.style.border="2px solid blue";
                oForm.password.style.outline="none";
                oForm.password.style.textIndent="16px";
                oForm.password.blur()//focus表单元素失去焦点的方法
            },5000)
        }
        </script>
    </head>
    <body>
        <button id="btn">提交表单</button>
        <form action="" name="register">
            <div>账号:<input type="text" name="account" value="请输入账号!"></div>
            <div>密码:<input type="password" name="password"></div>
            <div>性别:<input type="radio" name="sex" value="boy" checked>男<input type="radio" name="sex" value="girl">女<input type="radio" name="sex" value="unknown">未知</div>
            <div>
                爱好:<input type="checkbox" name="hobby" value="basketball" checked>篮球<input type="checkbox" name="hobby" value="football" checked>足球<input type="checkbox" name="hobby" value="pingpang">乒乓球
            </div>
            <div>家乡:<select name="city">
                <option value="1">西安市</option>
                <option value="2" selected>咸阳市</option>
                <option value="3">宝鸡市</option>
                <option value="4">渭南市</option>
                <option value="5">铜川市</option>
            </select></div>
            <div>
                座右铭:<textarea name="" id="" cols="30" rows="10"></textarea>
            </div>
            <input type="submit" value="注册">
        </form>
    </body>
    </html>
    表达元素的共同属性和方法

     


     18:操作FORM表单元素

    一:文本域

        value属性:设置或者获取值。

    二:单选按钮

        checked属性:返回或者设置单选的选中状态。true 选中,false 未选中。

        value属性:获取选中的值,必须先判断单选按钮是否被选中。

    三:多选按钮

        checked属性:返回或者设置单选的选中状态。true 选中,false 未选中。

        value属性:获取选中的值,必须先判断选中状态。

    四:下拉框

        selected属性:给option设置或返回下拉框的选中状态。true 选中,false 未选中。

        selectedIndex属性:设置或返回下拉框被选中的索引号。

    五:文本区域

        value属性:设置或者获取值。

    六:验证表单

    1:事件

           onsubmit  当表单提交的时候触发的事件。

           onblur    失去焦点。

           onfocus   获得焦点。

           onchange  下拉框改变值的时候。

    2:return false;  // 阻止事件的默认行为(适用于所有事件)。

    七:提交方法

    表单对象.submit();

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>获取表达元素</title>
        <script type="text/javascript">
            window.onload=function() {
            var oForm = document.register;
            // 获取FORM表单中的元素
            /*console.log(oForm.elements);//获取表达元素集合
            console.log(oForm.elements['account']);//通过元素名称的方式访问
            console.log(oForm.elements[0]);//通过元素在表单的下标的方式访问
            console.log(oForm.elements.account);//通过对象访问.方式访问
            //以上都是通过表单集合的方式访问表达元素
            console.log(oForm.account)//直接通过name(元素的name)的方式访问*/
            //表达元素的共同的属性和方法
    /*        console.log(oForm.city.value);//获取下拉框的选中值
            oForm.account.disabled = true;//账户按钮不可用,值:false可用
            console.log(oForm.account.form);//获取表单元素的所引用的表单
            //为看效果加延时器和改变样式
            setTimeout(function() {        
                oForm.password.style.border="2px solid red";
                oForm.password.style.textIndent="16px";
                oForm.password.style.outline="none";
                oForm.password.focus()
                //focus表单元素获取焦点的方法,效果同标签属性autofocus
            },2000)    
            setTimeout(function() {
                oForm.password.style.border="2px solid blue";
                oForm.password.style.outline="none";
                oForm.password.style.textIndent="16px";
                oForm.password.blur()//focus表单元素失去焦点的方法
            },5000)*/
    
            //操作form表单元素
    
            //一、—五、操作表单元素
            //更改账户的输入值
            oForm.account.value = '不想输入!';
            //循环输出性别的选中情况
            for(var i = 0; i < oForm.sex.length; i++) {
                console.log(oForm.sex[i].checked)
            }
            oForm.sex.value = 'unknown';
            for(var i = 0; i < oForm.hobby.length; i++) {
                //循环输出表单爱好选中的值
                if(oForm.hobby[i].checked) {
                    console.log(oForm.hobby[i].value)
                }
                //设置乒乓选项的值为选中
                if(oForm.hobby[i].value === 'pingpang') {
                    oForm.hobby[i].checked = true;
                }
            }
            var oCity = oForm.city;
            var aOptions = oCity.children;
            //设置城市北京市选中
            for(var i = 0; i < aOptions.length; i++) {
                if(aOptions[i].value == 4) {
                    aOptions[i].selected = true;
                }
            }
            //设置三亚市选中
            oCity.value = 2;
            console.log(oCity.selectedIndex)
            //以索引的方式设置广州市为选中
            oCity.selectedIndex = 4
    
            //六:验证表单
            var oAccount = oForm.account;
            //获取焦事件
            oAccount.onfocus = function () {
                this.value = '';
            }
            //失去焦点事件
            oAccount.onblur = function () {
                this.value = '请输入账号!';
            }
            //表单元素值改变事件,失去焦点时出发
            oAccount.onchange = function () {
                console.log(this.value)
            }
            //通过返回值的方式阻止表单提交
            oForm.onsubmit = function () {
                return false;
            }
            //七.表单提交方法
            //通过表单的方法提交表达
            var oBtn = document.getElementById('btn')
            oBtn.onclick = function () {
                oForm.submit();
            }
        }
        </script>
    </head>
    <body>
        <button id="btn">提交表单</button>
        <form action="" name="register">
            <div>账号:<input type="text" name="account" value="请输入账号!"></div>
            <div>密码:<input type="password" name="password"></div>
            <div>性别:<input type="radio" name="sex" value="boy" checked>男<input type="radio" name="sex" value="girl">女<input type="radio" name="sex" value="unknown">未知</div>
            <div>
                爱好:<input type="checkbox" name="hobby" value="basketball" checked>篮球<input type="checkbox" name="hobby" value="football" checked>足球<input type="checkbox" name="hobby" value="pingpang">乒乓球
            </div>
            <div>家乡:<select name="city">
                <option value="1">西安市</option>
                <option value="2" selected>三亚市</option>
                <option value="3">上海市</option>
                <option value="4">北京市</option>
                <option value="5">广州市</option>
            </select></div>
            <div>
                座右铭:<textarea name="" id="" cols="30" rows="10"></textarea>
            </div>
            <input type="submit" value="注册">
        </form>
    </body>
    </html>
    操作form表单元素

     

  • 相关阅读:
    修改Tarsphp节点线程数避免请求阻塞
    Docker删除所有容器
    清理mysql数据库binlog日志
    查看centos磁盘情况,查找大文件路径
    winform窗体的生命周期和事件加载顺序是什么?
    数据库自增ID用完了会怎么样?
    MPFIT for python
    Plplot中line width 问题
    剪切Postscript图片中的多余边框
    嵌入式下的深度学习 Sparkfun Edge with TensorFlow(一)Hello World
  • 原文地址:https://www.cnblogs.com/witkeydu/p/8352894.html
Copyright © 2011-2022 走看看