Home > Web Front-end > JS Tutorial > body text

Events in BOM, DOM and JS

大家讲道理
Release: 2018-05-17 15:58:24
Original
3212 people have browsed it

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>然后是setInterval与clearInterval</title>
        <!--要记得首先打开控制台哟~-->
        <script type="text/javascript">            var num = 10;            var timeinterval = setInterval(function(){
                num--;
                console.log(num);                if (num==0){
                clearInterval(timeinterval);
                }
            },1000)            function clearIntervalBtn(){
                clearInterval(timeinterval);
            }        </script>
    </head>
    <body>
        <button onclick="clearIntervalBtn()">clearIntervar</button>
    </body>
</html>
Copy after login

2.2 BOM’s side rooms—a brief description of other objects.

Because BOM objects other than window objects rarely appear in actual JS writing, this K will briefly mention them in the form of code.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>BOM的侧室们</title>
        <!--要记得首先打开控制台哟~-->
        
        <script type="text/javascript">            
            // screen对象            
            console.log(screen);
            console.log(screen.width);//宽度            console.log(screen.height);//高度            console.log(screen.availHeight);//可用高度=屏幕高度-底部任务栏            console.log(screen.availWidth);//可用宽度
            
            // location对象
            //   完整的url路径: 
            //   协议:// 主机名(IP地址):端口号(默认80端口)/文件路径?传递的参数(参数名0=参数值0&参数名1=参数值1)#锚点            
            console.log(location);
            console.log(location.href);//完整路径            console.log(location.protocol);//路径协议http: https: ftp: file: mailto:             console.log(location.pathname);//路径部分  /开始            console.log(location.port);//端口号            console.log(location.search);//从?开始往后的部分            console.log(location.hostname);//IP地址            console.log(location.host);//主机名+端口号            console.log(location.hash);//从#开始的锚点
            // 使用JS设置页面跳转
            //    window.location="http://www.baidu.com";
            
            function locationReload(){                //重新加载当前页面                location.reload(true);//reload(true)表示从服务器重新加载当前页面;reload()在本地刷新当前页面            }            
            function locationAssign(){
                location.assign("http://www.baidu.com");    //加载新的文档,替换以后可以回退            }            
            function locationReplace(){
                location.replace("http://www.baidu.com");//使用新的文档替换当前文档,替换后不能回退            }            
            // history
            // length : 浏览历史列表的个数
            // history.forward(); : 前进到前一个页面
            // history.back(); : 后退到后一个页面
            // history.go(); : 跳转到历史浏览历史的任意位置;当前页为第0个,前一个页面为第1个,后一个页面为第-1个            
            console.log(history.length);            
            function historyForword(){
                history.forward();
            }            function historyBack(){
                history.back();
            }            function historyGo(){
                history.go();                // 0 
                // 1 = history.forward();
                // -1 = history.back();            }            
            // Navigator            console.log(navigator.appName);//产品名称            console.log(navigator.appVersion);//产品版本号            console.log(navigator.userAgent);//用户代理信息            console.log(navigator.platform);//系统代理平台            
            console.log(navigator.plugins);//检查浏览器安装的插件信息
            // 返回一个数组,检测浏览器安装的所有插件(↓主要属性↓)
            // description : 插件描述信息
            // filename : 插件在本地磁盘的文件名
            // length : 插件的个数
            // name : 文件名        
            console.log(navigator.mimeTypes);//浏览器插件所支持的文件类型(↓主要属性↓)
            // description:MIME类型描述
            // enabledPlugin:支持此类型的浏览器插件
            // suffixes:此类型可能的后缀名
            // type:MIME类型的写法,例如:image/x-icon text/css
        </script>
        
    </head>
    <body>
        
        <button onclick="locationAssign()">加载新的文档</button>
        <br />
        
        <button onclick="locationReload()">重新加载当前文档</button>
        <br />
        
        <button onclick="locationReplace()">使用新的文档替换当前文档</button>
        <br />
        
        <button onclick="historyForword()">这个是historyForword</button>
        <br />
        
        <button onclick="historyBack()">这个是historyBack</button>
        <br />
        
        <button onclick="historyGo()">这个是historyGo</button>
        
    </body>
</html>
Copy after login

二、“N世同堂”——DOM

1、朝阳群众又立功,代码中竟出现如此神秘的“庞大组织”——DOM简介

    DOM(Document Object Model),是指文档对象模型,是W3C组织推荐的处理可扩展标志语言的标准编程接口。在网页上,组织页面(或文档)的对象被组织在一个树形结构中,用来表示文档中对象的标准模型,而DOM中的每一条分支都被称作一个“节点”,所有节点及节点属性构成的结构图会呈现出很强的层次性(栗子如下图,源于万能的度娘)。

    DOM节点分为三大类:元素节点,文本节点,属性节点。文本节点、属性节点为元素节点的两个子节点,通过gelElement系列方法,可以取到元素节点。

2、如此组织,其真相竟然是...——DOM操作详解

    DOM操作是JS中应用性非常强的一部分,所以本K就以代码的形式来给大家叙述。

2.1 获取节点与样式修改

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>DOM代码详述(一)</title>
        
        <script type="text/javascript">            

            
            window.onload = function(){                var p1 = document.getElementById("p1");//通过ID获取唯一的节点;多个同名ID只会取第一个                console.log(p1);
                
                console.log(p1.tagName);//查看节点:①属性;获取节点的标签名                console.log(p1.innerHTML);//②设置或者获取节点内部的所有HTML代码                console.log(p1.innerText);//③设置或者获取节点内部的所有文字                
                console.log(window.getComputedStyle(p1,null));//查看所有属性(非IE属性)                console.log(p1.currentStyle);//查看所有属性(IE属性)                
            }            function getById(){                //取到元素节点的样式属性节点
                var p1 = document.getElementById("p1").style;//获取                p1.backgroundColor = "#FF00FF";//行级样式表权重1000;所有节点属性,一律驼峰命名法
                
                //取到元素节点
                var pDoc = document.getElementById("p1");//获取                pDoc.innerHTML = "<s>king_land</s>";//重置修改p中的HTML代码            }            
            //——————————————分割线——————————————————
            
            function getByName(){//通过Name取到一个数组,包含1到多个节点;
                
                var p = document.getElementsByName("p1");
                
                console.log(p.length);                
                //使用方式:通过循环,取到每一个节点,循环次数从0开始,<数组.length
                for(var n = 0 ;n < p.length ; n++){
                    p[n].style.backgroundColor = "#FFFF00";
                }                
                //p1.backgroundColor = "#FFFF00";
                //p[0].style.backgroundColor = "#FFFF00";//★                
            }            
            //——————————————分割线——————————————————
            
            //document.getElementsByTagName();//同Name

            function getByTagName(){                
                var p = document.getElementsByTagName("p");
                
                p[0].style.backgroundColor = "#00FF00";
                
            }            
            //——————————————分割线——————————————————
            
            //document.getElementsByClassName();//同Name

            function getByClass(){                
                var p = document.getElementsByClassName("p1");
                
                p[0].style.backgroundColor = "#00FFFF";
                
            }            //——————————————分割线——————————————————
            
            function getAttr () {                
                var img1 = document.getElementById("img1");
                alert(img1.getAttribute("src"));
                
            }//查看属性节点 getAttribute("属性名");
            
            //——————————————分割线——————————————————
            
            function setAttr () {                
                var img1 = document.getElementById("img1");
                img1.setAttribute("src","../../2-CSS基础语法/img/bg_flower_multi.gif");
                img1.setAttribute("style","width: 100px;height: 100px;");
                
            }//设置属性节点 getAttribute("属性名","属性值");
            
            //——————————————分割线——————————————————
            
            //JS修改样式总结
            //1、.className:为元素设置一个新的class名字   例如:p1.className = "p2";
            //2、.style:为元素设置新的样式   例如:p1.style.background-color = "blue";
            //3、.style.cssText:为元素同时修改多个样式   例如:p1.style.cssText = "width:100px;height:200px;";
            

            
            
            
        </script>
        
        <style type="text/css">
            
            .p1{
                height: 100px;
                width: 100px;
                background-color: #000000;
                color: #FFFFFF;
                line-height: 100px;
                text-align: center;
            }
            
        </style>
        
        
    </head>
    <body>
        
        <p id="p1" name="p1" class="p1">
            这里是测试区
        </p>
        <p id="p1" name="p1" class="p1">
            这里是测试区
        </p>
        <p id="p1" name="p1" class="p1">
            这里是测试区
        </p>
        <img src="../../2-CSS基础语法/img/bg_flower_multi.gif" id="img1"/>
        
        
        <br />
        <button onclick="getById()">通过ID修改pcolor</button>
        <br />
        <button onclick="getByName()">通过Name修改pcolor</button>
        <br />
        <button onclick="getByTagName()">通过TagName修改pcolor</button>
        <br />
        <button onclick="getByClass()">通过ClassName修改pcolor</button>
        <br />
        <button onclick="getAttr()">取到img的src属性值</button>
        <br />
        <button onclick="setAttr()">修改img的src属性值</button>
        
    </body>
</html>
Copy after login

2.2 层次节点常用操作

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        
        <script type="text/javascript">
            
                window.onload = function (){                    
                    //获取层次节点的常用属性
                    
                    var ul1 = document.getElementById("ul1");                    
//                    var lis = ul1.getElementsByTagName("li");  //只取到ul1中所有li//                    var lis = document.getElementsByTagName("li");  //取到页面中所有的li
                    console.log(ul1.childNodes);//获取元素的所有子节点(包含元素节点、文本节点)                    
                    console.log(ul1.firstChild);//获取元素的第一个子节点                    
                    console.log(ul1.lastChild);//获取元素的最后一个子节点                    
                    console.log(ul1.ownerDocument);//获取当前文档根节点,在html文档中为document节点                    
                    console.log(ul1.parentNode);//获取当前节点的父节点                    
                    console.log(ul1.previousSibling);//获取当前节点的前一个兄弟节点                    
                    console.log(ul1.nextSibling);//获取当前节点的后一个兄弟节点
                    
                    //上述属性均会获得所有的元素节点和文本节点,如果只需要元素节点,需要使用对应Element属性,例如:firstChild→firstElementChild                    
                    console.log(ul1.attributes);//获取当前节点的所有属性节点                    
                }                
                //——————————————创建并新增节点——————————————————
                    
                //方法一:.creatElement("标签名")创建一个新节点,需要配合setAttribute()方法设置属性;
                //方法二:.appendChild(节点名)在元素的最后追加一个新节点
                //方法三:.insertBefore(新节点名,目标节点名):将新节点插入到目标节点之前
                //方法四:克隆对象.cloneNode(true/false):需要克隆谁,就用谁去调用克隆节点;传递参数可以为true/false,true表示克隆当前节点及子节点;false表示只克隆当前节点,不克隆子节点。
                    
                function appendImg(){                    
                    //1、创建一个图片节点
                    var img = document.createElement("img");                    //2、给img节点设置属性                    img.setAttribute("src","../../1-HTML基本标签/ivicon.png");                    //3、将设置好的img节点追加到body最后                    document.body.appendChild(img)//.setAttribute("src","../../img/2017-02-25_143342.png");                    
                }                
                function insertImg(){                    
                    //1、创建一个图片节点
                    var img = document.createElement("img");                    //2、给img节点设置属性                    img.setAttribute("src","../../1-HTML基本标签/ivicon.png");                    //3、在两个ul之间插入图片
                    var ul2 = document.getElementById("ul2");
                    document.body.insertBefore(img,ul2);
                    
                }                var count = 2;                function copyUl(){                    
                    //1、取到ul2节点
                    var ul2 = document.getElementById("ul2");                    //2、克隆节点
                    var ul2Clon = ul2.cloneNode(true);
                    count ++;
                    ul2Clon.setAttribute("id","ul"+count)                    //3、在原ul2节点之前,插入新克隆节点                    document.body.insertBefore(ul2Clon,ul2);
                    
                }                
                //——————————————删除和替换节点——————————————————
                
                //1、.removeChild(需删除节点):从父容器中删除指定节点;
                //2、.replaceChild(新节点,被替换节点):用新节点替换被指定节点,如果新节点为页面中已有节点,会将此节点删除后替换到指定节点。
                
                function deleteUl1(){                    
                    //取到ul1
                    var ul1 = document.getElementById("ul1");                    if (ul1){                        //从父容器body中删除ul1节点                        document.body.removeChild(ul1);
                    }else{
                        alert("憋删了,早没了");
                    }
                    
                }                
                function ul1ReplaceUl2(){                    
                    var p = document.createElement("p");
                    p.setAttribute("style","width: 100px;height: 100px;background-color: #20B2AA;");                    var ul2 = document.getElementById("ul2");
                    document.body.replaceChild(p,ul2);
                    
                }                
        </script>
        
        <style type="text/css">
            
            ul{
                width: 600px;
                list-style: none;
                padding: 0;
                background-color: #20B2AA;
                display: flex;
                justify-content: space-around;
                margin-top: 20px;
            }
        
        </style>
        
    </head>
    <body>
        
        <ul id="ul1">
            <li>第一项</li>
            <li>第二项</li>
            <li>第三项</li>
            <li>第四项</li>
        </ul>
        
        <ul id="ul2">
            <li>第1项</li>
            <li>第2项</li>
            <li>第3项</li>
            <li>第4项</li>
        </ul>
        
        <button onclick="appendImg()">在最后插入一幅图片</button>
        <button onclick="insertImg()">在两个ul之间插入一幅图片</button>
        <button onclick="copyUl()">copy一个ul2</button>
        <br />
        
        <button onclick="deleteUl1()">删除ul1</button>
        <button onclick="ul1ReplaceUl2() ">用ul1替换ul2</button>
        
        
        
        
    </body>
</html>
Copy after login

2.3 表格操作

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>DOM操作表格</title>
        
        <script type="text/javascript">            
            //表格对象:
            //1、rows属性:返回表格中的所有行,数组;
            //2、insertRow(index):在表格的第index+1行,插入一个新行;
            //3、deleteRow(index):删除表格的第index+1行;
            
            //表格的行对象:
            //1、cells属性:返回当前行中的所有单元格,数组;
            //2、rowIndex属性:返回当前行在表格中的索引顺序,从0开始;
            //3、insertCell(index):在当前行的index+1处插入一个td;
            //4、deleteCell(index):删除当前行的第index+1个td;
            
            //表格的单元格对象:
            //1、cellIndex属性:返回单元格在该行的索引顺序,从0开始;
            //2、innerHTML属性:设置或者返回当前单元格中的HTMl代码;
            //3、align(valign)属性:设置当前单元格的水平对齐方式;
            //4、className属性:设置单元格的class名称。
            
            function newRow(){                
                var book = prompt("书名:");                var price = prompt("价格:");                
                var table = document.getElementsByTagName("table");                //在表格的最后一行插入一个新行
                var newRow = table[0].insertRow(table[0].rows.length-1);                //给新行设置单元格
                var cell0 = newRow.insertCell(0);
                cell0.innerHTML = book;                var cell1 = newRow.insertCell(1);
                cell1.innerHTML = price;
                
                getSum();
                
            }            
            function deleteRow(){                
                var table = document.getElementsByTagName("table");                if(table[0].rows.length>2){
                    table[0].deleteRow(table[0].rows.length-2);
                }else{
                    alert("删删删!删你妹啊删!")
                }
                getSum();
            }            
            function changeTitle(){                
                var color = prompt("请输入6位十六进制颜色值:");                var table = document.getElementsByTagName("table");
                table[0].rows[0].style = "background-color:#"+color;
                
            }            
            function copyRow(){                
                var table = document.getElementsByTagName("table");                var copyRow = table[0].rows[table[0].rows.length-2].cloneNode(true);                var heJi = table[0].rows[table[0].rows.length-1];                //由于浏览器,自动将表格的<tr>包裹在<tbody>中
                //所以<tr>实际并非<table>的子节点,故需取到<table>中的<tbody>进行插入;
                
                if(table[0].rows.length>2){
                    table[0].getElementsByTagName("tbody")[0].insertBefore(copyRow,heJi);
                }else{
                    alert("没有可以复制的行");
                }
                getSum();
            }            
            function getSum(){                //取到当前表格 表格所有行
                var table = document.getElementsByTagName("table");                var rows = table[0].rows;                //                if(rows.length<=2){
                    rows[rows.length-1].cells[1].innerText = 0 + "元";
                    alert("没有可计算的行!");                    return;
                }                //求和
                var sum = 0 ;                
                for(var i = 1 ; i <= rows.length-2 ; i++){//第0行与最后一行舍弃1  rows.length-2
                    
                    var cells = rows[i].cells;//取到单元格                    sum += parseFloat(cells[cells.length-1].innerText);//最后一个单元格的  内容(innerText) 转化成数字并求和计算!                    
                }
                
                rows[rows.length-1].cells[cells.length-1].innerText = sum.toFixed(2) + "元";
                
            }
            
            window.onload = function(){
                getSum();
            }            
            
        </script>
        
        <style type="text/css">
            
            table{
                border-collapse: collapse;
                width: 400px;
                text-align: center;
                color: #585858;
            }
            td,th{
                border: 1px solid #8B8A8B;
            }
            table tr:last-child{
                color: #E70014;
            }
            
        </style>
        
    </head>
    <body>
        
        
        <table>
            <tr>
                <th>书名</th>
                <th>价格</th>
            </tr>
            <tr>
                <td>看得见风景的房间</td>
                <td>30.00元</td>
            </tr>
            <tr>
                <td>幸福从天而降</td>
                <td>18.50元</td>
            </tr>
            <tr>
                <td>60个瞬间</td>
                <td>32.00元</td>
            </tr>
            <tr>
                <td>合计</td>
                <td></td>
            </tr>
        </table>
        
        <br />
        
        <button onclick="newRow()">增加一行</button>
        <button onclick="deleteRow()">删除最后一行</button>
        <button onclick="changeTitle()">修改标题样式</button>
        <button onclick="copyRow()">复制最后一行</button>
        

    </body>
</html>
Copy after login

三、鼠标和键盘、那些不得不说的事——JS中的事件

1、三足鼎立——JS中的事件分类

1.1 鼠标事件

click 单击

dblclick 双击

mouseover 鼠标移入

mouseout 鼠标移出

mousemove 鼠标划过

mousedown 鼠标按下

mouseup 鼠标抬起

1.2 键盘事件

keydown:键盘按下时触发

keypress:键盘按下并松开的瞬间触发

keyup:键盘抬起时触发

Notes
①Execution sequence: keydown keypress keyup
②When long pressed, it will be executed continuously in a loop keydown keypress
③There is a keydown event, but there may not be a keyup event (during the event triggering process, if the mouse is moved, there may be no keyup)
④The keypress event can only be captured Letters, numbers, and symbols (including carriage returns and spaces) cannot capture function keys; keydown keyup can basically capture all function keys, with special exceptions
⑤keypress is case-sensitive, keydown keyup is not;
⑥keypress does not distinguish between the main keyboard and the small keyboard, but keydown keyup does;
[How to determine the keyboard trigger key]
⑴ In the trigger function , the trigger parameter e represents the key event;
⑵ Confirm the case Ascii code value through e.keyCode, and then determine the key;
⑶ Compatible with all browsers (generally unnecessary):
var evn = e||event; //Get the button
var code = evn .keyCode||evn.which||evn.charCode; //Get the key code

1.3 HTML event

2. This shore and the other shore - event model in JS

2.1 DOM0 event model

2.1. 1 Inline model: directly use the function name as the attribute value of an event attribute of the HTML tag; ;/button>
Disadvantages: Violates W3C’s basic principle
on the separation of HTML and JS! 2.1.2 Script model: Binding through event attributes in JS script;


# Limitations: The same node can only be bound to one event of the same type;
2.2 DOM2 event model (there will be chestnuts later!)

Advantages: Multiple listeners for events of the same type can be added to the same node;

①添加事件绑定:
IE10之前:btn1.attachEvent("onclick",函数);
其他浏览器:btn1.addEventListener("click",函数,true/false);
true:表示事件捕获;false(默认):表示事件冒泡
兼容写法:if(btn1.attackEvent){btn1.attachEvent("onclick",函数);}else{btn1.addEventListener("click",函数,true/false);}
②取消事件绑定:
.detachEvent("onclick",函数名);
.removeEventListener("click",函数名);
注:如果取消时间帮顶,回调函数必须使用有名函数,而不能使用匿名函数。因为在取消事件帮顶时,需要传入函数名;

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>这里是栗子</title>
        
        <script type="text/javascript">
            window.onload = function (){                
                var btn1 = document.getElementById("btn1");                function func1(){
                    alert(1);
                }                function func2(){
                    alert(2);
                }
                btn1.addEventListener("click",func1,false);
                btn1.addEventListener("click",func2,false);                
                var btn2 = document.getElementById("btn2");
                btn2.addEventListener("click",function(){
                    btn1.removeEventListener("click",func1);
                },false);
                
            }        </script>
    </head>
    <body>
        
        <button id="btn1">点我会弹窗!</button>
        
        <br /><br />
        
        <button id="btn2">点我不弹窗!</button>
    </body>
</html>
Copy after login

3、上上下下——JS中的事件流

3.1 事件冒泡

当某DOM元素触发某事件时,会从当前DOM元素开始,逐个触发其祖先元素的同类型事件,直到DOM根节点;
DOM0事件流均为事件冒泡;
IE中使用.attachEvent()事件,均为冒泡;
其他浏览器.addEventListener()添加的事件,当第三个参数为false时,为冒泡。

3.2 事件捕获

当某DOM元素触发某事件时,会从DOM根节点,逐个触发其祖先元素的同类型事件,直到触发到当前DOM元素开始;

只有使用.addEventListener()添加的事件,并且当第三个参数为true时,才进行捕获。

3.3 阻止事件冒泡

IE浏览器:将e.cancelBubble属性设为true;
其他浏览器:调用e.stopPropagation();方法

3.4 取消事件默认行为

IE浏览器:将e.returnValue属性设为false;
其他浏览器:调用e.preventDefault(); 方法

(这里有栗子)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>事件流举栗</title>
        <style type="text/css">
            
            #p1{
                width: 200px;
                height: 200px;
                background-color: #20B2AA;
                color: #FFFFFF;
                font-size: 20px;
                font-weight: 700;
            }
            #p2{
                width: 100px;
                height: 100px;
                background-color: #436690;
                color: #FFFFFF;
                font-size: 20px;
                font-weight: 700;
            }
            #p3{
                width: 50px;
                height: 50px;
                background-color: #4E2E83;
                color: #FFFFFF;
                font-size: 20px;
                font-weight: 700;
            }
            
        </style>
        
    </head>
    <body>
        <p id="p1">
            <p id="p2">
                <p id="p3">3</p>
                2
            </p>
            1
        </p>

        <a href="../07 JS中的DOM/笔记.html" onclick="stopHref()">跳转页面</a>
    </body>
    
    <script type="text/javascript">        var p1 = document.getElementById("p1");        var p2 = document.getElementById("p2");        var p3 = document.getElementById("p3");
        
        p1.addEventListener("click",function(e){
            handleE();
            console.log("p1触发了click事件");
        },false);
        
        p2.addEventListener("click",function(e){
            handleE();
            console.log("p2触发了click事件");
        },false);
        
        p3.addEventListener("click",function(e){
            handleE();
            console.log("p3触发了click事件");
        },false);        function handleE(e){            var evn = e||window.event;
            evn.stopPropagation();    
        }        function stopHref(e){
            
            e = e||window.event;            if (e.preventDefault) {
                e.preventDefault(); //IE以外             } else {
                e.returnValue = false; //IE                 }

            alert("好气呀!");
            
        }        
    </script>
    
</html>
Copy after login

The above is the detailed content of Events in BOM, DOM and JS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template