Dom和Bom重点部分

77 阅读3分钟

DOM

1.1DOM的概念

常见的使用:HTML DOM 是关于如何获取、更改、添加或删除 HTML 元素的标准...

更改元素的背景颜色,等价的

   var arr1= document.getElementsByTagName("div");
    for(let i of arr1){
        i.style.background="red";
    }
/*
    for(let i=0;i<arr1.length;i++){
        arr1[i].style.background="red";
    }
*/

1.2元素的获取方式

推荐使用CSS选择器获取元素

1.3事件*

1.点击事件

后面定义的点击事件将覆盖前面的事件。

2.鼠标事件

//html
<div>
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
        </ul>
    </div>
//js
for(let ele of document.querySelectorAll("li")){
            ele.onmouseover = function(){
                ele.style.backgroundColor="red";//将背景色改为红色
        }
        ele.onmouseout=function(){
            ele.style.backgroundColor="white";
        }
    }

3.焦点事件

//css
input{
            color: gray;
        }
//html
<input type="text" class="inpt" value="请输入内容">
//js
let txt=document.querySelector(".inpt")
    txt.onfocus=function(){
        if(txt.value=="请输入内容"){
            console.log("获取焦点");
            txt.value="";
            txt.style.color="black";
        }
    }
    txt.onblur=function(){
        // console.log("失去焦点");
        if(txt.value.length==0){
            txt.value="请输入内容";
            txt.style.color="gray";
        }
    }

4.事件的监听

5.事件参数e

Event 对象代表事件的状态

常用情况:事件在其中发生的元素键盘按键的状态、鼠标的位置、鼠标按钮状态

//html

//js

let btn1=document.querySelector(".btn");

        btn1.onclick=f1;

        btn1.onmouseover=f1;

        btn1.onmouseout=f1;

        function f1(e){

            console.log(e.type);

            switch(e.type){

                case "click":alert("点击");break;

                case "mouseover":this.style.backgroundColor="red";break;

                case "mouseout":this.style.backgroundColor="green";break;

            }

        }

*6.事件冒泡

像水泡一样从里到外。

点击div3的相关元素时,会触发div1、div2

试一试


//html
<div id="div1">
        <div id="div2">
            <div id=div3></div>
        </div>
    </div>
//css
#div1{
            width: 500px;
            height: 500px;
            background-color: pink;
        }
        #div2{
            width: 400px;
            height: 400px;
            background-color: rgb(22, 60, 210);
        }
        #div3{
            width: 300px;
            height: 300px;
            background-color: rgb(126, 216, 70);
        }
    //js
        document.querySelector("#div1").onclick = function(){
            console.log("div1");
        }
        document.querySelector("#div2").onclick = function(){
            console.log("div2");
        }
        document.querySelector("#div3").onclick = function(){
            console.log("div3");
        }

7.综合案例

案例:购物车商品总价

for 属性规定 label 与哪个表单元素绑定。

试一试

<div>
        <label for="inputUnitPrice">商品单价</label>
        <input type="number" class="inputUnitPrice" value="5">
    </div>
    <div>
        <label >商品数量</label>
        <button class="btnSub">-</button><span class="spanAmount">2</span><button class="btnAdd">+</button>
    </div>
    <div>
        总价格:<strong><span class="spanTotalPrice">10</span></strong>
    </div>
//js
// 获取元素
        let inputUnitPrice=document.querySelector(".inputUnitPrice");
        let spanAmount=document.querySelector(".spanAmount");
        let spanTotalPrice=document.querySelector(".spanTotalPrice");
        let btnSub=document.querySelector(".btnSub");
        let btnAdd=document.querySelector(".btnAdd");
        //事件处理
        btnAdd.onclick=function() {
            let amount=spanAmount.innerText;
            let unitPrice=inputUnitPrice.value;
            amount++;
            spanAmount.innerText=amount;
            spanTotalPrice.innerText=amount*unitPrice;
        }
        btnSub.onclick=function() {
            let amount=spanAmount.innerText;
            let unitPrice=inputUnitPrice.value;
            amount=--amount>=0?amount:0;
            spanAmount.innerText=amount;
            spanTotalPrice.innerText=amount*unitPrice;
        }
        inputUnitPrice.oninput=function(){
            let unitPrice=inputUnitPrice.value>=0?inputUnitPrice.value:0;
            let amount=spanAmount.innerText;
            spanTotalPrice.innerText=amount*unitPrice;
        }

案例:表格全选

border-spacing 属性设置相邻单元格的边框间的距离(仅用于“边框分离”模式)。

注释:某些版本的IE浏览器不支持此属性。**

试一试

<table>
        <thead>
            <tr>
                <th>
                    <input type="checkbox" class="cbAll">
                </th>
                <th>菜名</th>
                <th>饭店</th>
            </tr>
        </thead>
        <tbody class="t_body">
            <tr>
                <td><input type="checkbox"></td>
                <td>红烧肉</td>
                <td>盖浇饭</td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>西红柿</td>
                <td>茄子</td>
            </tr>
        </tbody>
    </table>
//css
table,
        th,
        td {
        border: 1px solid;
        }

        table {
        border-spacing: 0;
        }
        th{
            background-color: rgb(32, 153, 218);
        }
        td{
            font-size: 12px;
        }
        th,
        td {
        padding: 5px 10px;
        border-top-width: 0;
        border-left-width: 0;
        }

        th:last-child,
        td:last-child {
        border-right-width: 0;
        }

        tr:last-child td {
        border-bottom-width: 0;
        }
//js
let cbAll=document.querySelector(".cbAll");
        let cbItems=document.querySelectorAll(".t_body input");
        //控制全选
        cbAll.onclick=function(){
            console.log(this.checked);
            for(let cbItem of cbItems){
                cbItem.checked=this.checked;
            }
        }
        //循环单选框,第一个循环选择的单选框注册。第二个,若有一个未选,则设置flag=false;全选控制全选=flag。
        for(let cbItem of cbItems){
            cbItem.onclick=function(){
                let flag=true;
                for(let cbItem of cbItems){
                    if(!cbItem.checked){
                        flag=false;
                        break;
                    }
                }
                cbAll.checked=flag;
            }
        }

点提示

事件参数e: 事件在其中发生的元素键盘按键的状态、鼠标的位置、鼠标按钮状态

*冒泡函数:*像水泡一样从里到外触发。

*for *属性规定 label 与哪个表单元素绑定。

border-spacing 属性设置相邻单元格的边框间的距离(仅用于“边框分离”模式)。

1.4节点*

1、节点的概念

代码的节点,与源代有关

代码示例

<div id="dv">哦哦
        <span>这是第一个span标签</span>
        <p>这是div中的第二个元素,第一个p标签</p>
        <ul id="ulNames">
            <li>乔峰</li>
            <li>虚竹</li>
            <li id="three">段誉</li>
            <li>简历发我</li>
        </ul>
    </div>
    <script>
        let ulNames=document.querySelector("#ulNames");
        console.log(ulNames.childNodes);//节点
        console.log(ulNames.children);//元素
    </script>

*2.获取节点

父节点

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>父节点</title>
</head>
<body>
    <div id="dv">哦哦
        <span>这是第一个span标签</span>
        <p>这是div中的第二个元素,第一个p标签</p>
        <ul id="ulNames">
            <li>乔峰</li>
            <li>虚竹</li>
            <li id="three">段誉</li>
            <li>简历发我</li>
        </ul>
    </div>
    <script>
        let ulNames=document.querySelector("#ulNames");
        console.log("父节点");
        console.log(ulNames.parentNode);//div
        console.log(ulNames.parentNode.parentNode);//body
        console.log(ulNames.parentNode.parentNode.parentNode);//html
        console.log(ulNames.parentNode.parentNode.parentNode.parentNode);//document
        console.log(ulNames.parentNode.parentNode.parentNode.parentNode.parentNode);//null
        console.log("----------------");
        console.log("父元素");
        console.log(ulNames.parentElement);//div
        console.log(ulNames.parentElement.parentElement);//body
        console.log(ulNames.parentElement.parentElement.parentElement);//html
        console.log(ulNames.parentElement.parentElement.parentElement.parentElement);//null
        console.log(ulNames.parentElement.parentElement.parentElement.parentElement.parentElement);//报错
    </script>
</body>
</html>

子节点

子节点元素用的多

示例使用节点实现换行变色:

试一试

<button class="btn">换行变色</button>
    <div id="dv">哦哦
        <span>这是第一个span标签</span>
        <p>这是div中的第二个元素,第一个p标签</p>
        <ul id="ulNames">
            <li>乔峰</li>
            <li>虚竹</li>
            <li id="three">段誉</li>
            <li>简历发我</li>
        </ul>
    </div>
    <script>
        //第一种方法(推荐)
        document.querySelector(".btn").onclick = function(){
            let count=1;
            //遍历ulNames的子节点,每遍历一次count+1。
            for(let child of document.querySelector("#ulNames").children){
                child.style.backgroundColor=count%2==0?"red":"yellow";
                count++;
            }
        }
        //第二种类方法
        document.querySelector(".btn").onclick = function(){
            let count=1;
            for(let child of document.querySelector("#ulNames").childNodes){
                if(child.nodeType==1&&child.nodeName=="LI"){//需要判断子点类型
                    child.style.backgroundColor=count%2==0?"red":"yellow";
                    count++;
                }
            }
        }
        //第三种方法
        document.querySelector(".btn").onclick = function(){
            let count=1;
            for(let liEle of document.querySelectorAll("#ulNames>li")){//利用后代选择器
                liEle.style.backgroundColor=count%2==0?"red":"yellow";
                count++;
            }
        }

首尾与兄弟节点

ElementChild**使用的比较多

*操作节点

//html
<button class="btnAdd">创建一个p标签在下方</button>
    <div id="dv">
        <!-- <p>这是一个p标签</p> -->
    </div>

//js
        //第一种
        // document.querySelector(".btnAdd").onclick = function(){
        //     document.write("<p>这是一个p标签</p>")
        // }
        //第二种
        // document.querySelector(".btnAdd").onclick = function(){
        //     document.querySelector("#dv").innerHTML ="<p>这是一个p标签</p>";
        // }
        //第三种(推荐)
        let tagP=document.createElement("p");
        tagP.innerText="这是一个p标签";
        document.querySelector(".btnAdd").onclick = function(){
            document.querySelector("#dv").appendChild(tagP);//append Child:追加子项
        }

删除一个元素

    <button class="btnDel">删除下方一个p标签</button>
//js
document.querySelector(".btnDel").onclick = function(){
            document.querySelector("#dv").removeChild(tagP);//remove Child:删除子项
        }

遗留问题:为什么只能添加一个子项????

答:因为只生成了一次子项。

综合案例

1.创建列表结构

试一试

<button class="btn">添加ul列</button>
    <div id="dv">
    </div>
msgList=["生效","语言","化学","网络"];
        document.querySelector(".btn").onclick=function(){
        let tagUl=document.createElement("ul");
        for(let msgLi of msgList){
        let tagLi=document.createElement("li");//在循环下的话每次循环将生成新的li,不会只生成一个li的情况
            tagLi.innerText=msgLi;
            // console.log(msgLi);
            tagUl.appendChild(tagLi);
            tagLi.onmouseover=mouseover;
            tagLi.onmouseout=mouseout;
        }
        document.querySelector("#dv").appendChild(tagUl);
        }
        function mouseover(){
            this.style.backgroundColor="yellow";
        }
        function mouseout() {
            this.style.backgroundColor="";     
        }
2.创建删除按钮

试一试

<input type="button" value="创建按钮" class="btnAdd">
    <input type="button" value="删除一个子元素" class="btnDel">
    <input type="button" value="删除所有子元素" class="btnDelAll">
    <div id="dv"></div>
<input type="button" value="创建按钮" class="btnAdd">
    <input type="button" value="删除一个子元素" class="btnDel">
    <input type="button" value="删除所有子元素" class="btnDelAll">
    <div id="dv"></div>
    <script>
        let i=0;
        let btnAdd=document.querySelector(".btnAdd");
        let btnDel=document.querySelector(".btnDel");
        let btnDelAll=document.querySelector(".btnDelAll");
        let dv=document.querySelector("#dv");
        btnAdd.onclick=function(){
            let btn=document.createElement("input");
            let br=document.createElement("br");
            i++;
            btn.type="button";
            btn.value="按钮"+i;
            // dv.appendChild(btn);
            // dv.appendChild(br);
            dv.insertBefore(btn,dv.firstChild);//插入需要告诉位置
            dv.insertBefore(br,dv.firstChild);
        }
        btnDel.onclick=function(){
            dv.removeChild(dv.firstChild);
            dv.removeChild(dv.firstElementChild);  //删掉我们创建的br,换行符!!!
        }
        btnDelAll.onclick=function(){
            while(dv.firstElementChild){//一直删,直到第一个元素和节点没有才结束
                dv.removeChild(dv.firstChild);
                dv.removeChild(dv.firstElementChild);
            }
            i=0;//重新赋值而已
        }

重点提示

createElement的使用方法,firstChild节点,firstElementChild元素(在上面删除br元素用的); document.createElement("input"); dv.removeChild(dv.firstChild); dv.removeChild(dv.firstElementChild);

BOM

BOM都是以*window*作为调用对象

window.history.back();

概念

BOM(Browser Object Model)浏览器对象模型,与浏览器窗口进行互动的对象结构。*window*对象是BOM的顶层对象。

常见的使用:浏览器刷新,后退,前进,在浏览器中输入URL...

2.1window对象

所有浏览器都支持 window 对象。它代表浏览器的窗口

函数调用window.fu()=fu()

内置函数:alert()prompt()confirm()...通通是window调用的

窗口尺寸

两个属性可用用于确定浏览器窗口尺寸

  • window.innerHeight - 浏览器窗口的内高度(px)
  • window.innerWidth - 浏览器窗口的内宽度(以像素计)

浏览器窗口(浏览器视口)不包括工具栏和滚动条。

对于 Internet Explorer 8, 7, 6, 5:

  • document.documentElement.clientHeight
  • document.documentElement.clientWidth

  • document.body.clientHeight
  • document.body.clientWidth

一个实用的 JavaScript 解决方案(包括所有浏览器):

试一试

<p id="demo"></p>
//js
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

var x = document.getElementById("demo");
x.innerHTML = "浏览器内窗宽度:" + w + ",高度:" + h + "。";

该例显示浏览器窗口的高度和宽度:(不包括工具栏和滚动条)

其他窗口方法

一些其他方法:

  • window.open() - 打开新窗口
  • window.close() - 关闭当前窗口
  • window.moveTo() -移动当前窗口
  • window.resizeTo() -重新调整当前窗口

2.2定时器*

setInterval每隔一秒刷新当前时间,及清除定时器的用法

toLocaleString()获取当前设备的时间串

试一试

<button class="btn">停止定时器</button>
    <div id="time"></div>
//为定时器命名
      let showTime = setInterval(function() {//每隔多少时间执行一次函数
            let dateTime = new Date();
            document.querySelector("#time").innerHTML=dateTime.toLocaleString();
        },1000);
        document.querySelector(".btn").onclick=function() {
            window.clearInterval(showTime);//清除特定名称的定时器
        }

setTimeout用法一致,只执行一次

2.3加载

页面渲染完成才加载

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>onload</title>
    <script>
        // document.querySelector("#box").style.backgroundColor ="yellow";
        window.onload = function() {//页面渲染完成才加载
        document.querySelector("#box").style.backgroundColor ="yellow";
        }
    </script>
</head>
<body>
    <div id="box" style="width: 200px;height: 200px;border: 10px solid #e11919;"></div>
</body>
</html>

取消script里面第一行的注释,看看效果

2.4定位

了解

console.log(window.location);

<input type="button" value="跳转" id="btn">
//location对象
        console.log(window.location);
        //地址栏#后面的内容
        console.log(window.location.hash);
        //主机名及端口号
        console.log(window.location.host);
        //主机名
        console.log(window.location.hostname);
        //文件的路径--相对路径
        console.log(window.location.pathname);
        //端口号
        console.log(window.location.port);
        //协议
        console.log(window.location.protocol);
        //搜索的内容?后面
        console.log(window.location.search);

        onload = function(){
            document.querySelector("#btn").onclick=function(){
                location.href="http://106.54.43.103";//地址重定向(重要)
            }
        }
hash:地址栏#后面的内容

host:主机名及端口号

hostname:主机名

pathname:文件的路径--相对路径

port:端口号

protocol:协议 

search:搜索的内容?后面

重要:地址重定向

location.href="http://106.54.43.103";

2.5histroy前进、后退

控制浏览器前进、后退

<input type="button" value="后退" id="btn" >
document.querySelector("#btn").onclick =function(){
            window.history.back();
        }

*2.6本地存储localStorage

<input type="button" value="获取本地存储数据" id="btn">
window.onload=function(){ window.localStorage.setItem("student",JSON.stringify({id:1,name:"jack"})) } document.querySelector("#btn").onclick=function(){ let student = JSON.parse(localStorage.getItem("student")); console.log(student); }