Front-end basis of the BOM and DOM:

Front-end basis of the BOM and DOM

Foreword

到目前为止,我们已经学过了JavaScript的一些简单的语法。但是这些简单的语法,并没有和浏览器有任何交互。

也就是我们还不能制作一些我们经常看到的网页的一些交互,我们需要继续学习BOM和DOM相关知识。

JavaScript分为 ECMAScript,DOM,BOM。


BOM(Browser Object Model)是指浏览器对象模型,它使 JavaScript 有能力与浏览器进行“对话”。

DOM (Document Object Model)是指文档对象模型,通过它,可以访问HTML文档的所有元素。


Window对象是客户端JavaScript最高层对象之一,由于window对象是其它大部分对象的共同祖先,在调用window对象的方法和属性时,可以省略window对象的引用。例如:window.document.write()可以简写成:document.write()。

window object

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

*如果文档包含框架(frame 或 iframe 标签),浏览器会为 HTML 文档创建一个 window 对象,并为每个框架创建一个额外的 window 对象。

*没有应用于 window 对象的公开标准,不过所有浏览器都支持该对象。

所有 JavaScript 全局对象、函数以及变量均自动成为 window 对象的成员。

全局变量是 window 对象的属性。全局函数是 window 对象的方法。

接下来要讲的HTML DOM 的 document 也是 window 对象的属性之一。

BOM and DOM manipulation

BOM浏览器对象模型(了解)
        操作浏览器
DOM文档对象模型(******)
        操作html文档

DOM learning process

1. How to find the label

基本查找
查找标签如果要用变量临时存储 变量名的命名建议你使用以下格式
divEle = document.getElementByTagName('div')[0]

2. How to operate label

事件
一旦标签达到某个条件就会自动触发一系列的动作
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script>
    // function show() {
    //     alert('123')
    // }
    // let t = setTimeout(show,3000); // 三秒钟之后执行show函数
    // clearTimeout(t)  // 清除定时器


    function show() {
        alert(123)
    }
    function func(){
        let t = setInterval(show,3000);
        function inner(){
            clearInterval(t)
        }
        setTimeout(inner,9000)
    }
    func()

</script>
</body>
</html>

Binding two ways of events

What then executed after 1.onload finished loading wait

1.onload  等待什么什么加载完毕之后再执行
    <script>
            window.onload = function () {
                function func() {
                alert(123)
                }

                var btnEle = document.getElementById('d1');
                btnEle.onclick = function () {  // 给btn标签绑定一个点击事件  一旦被点击了 就会自动执行函数
                    alert(456)
                }
                }
                        
    </script>

2. Direct written in the body at the bottom (******)

我们在通过script标签引入外部js文件的时候
    通常也是写在body最下方

Some commonly used Window methods:

window.innerHeight - 浏览器窗口的内部高度
window.innerWidth - 浏览器窗口的内部宽度
window.open() - 打开新窗口
window.close() - 关闭当前窗口

1577693967938

window child objects

浏览器对象,通过这个对象可以判定用户所使用的浏览器,包含了浏览器相关信息。
navigator.appName  // Web浏览器全称
navigator.appVersion  // Web浏览器厂商和版本的详细字符串
navigator.userAgent  // 客户端绝大部分信息
navigator.platform   // 浏览器运行所在的操作系统

1577693995965

screen objects (to understand)

屏幕对象,不常用。

一些属性:

screen.availWidth - 可用的屏幕宽度
screen.availHeight - 可用的屏幕高度

history object (to understand)

window.history 对象包含浏览器的历史。

浏览历史对象,包含了用户对当前页面的浏览历史,但我们无法查看具体的地址,可以简单的用来前进或后退一个页面。
history.forward()  // 前进一页
history.back()  // 后退一页

1577693920796

The location object

window.location 对象用于获得当前页面的地址 (URL),并把浏览器重定向到新的页面。

Common properties and methods:

location.href  获取URL
location.href="URL" // 跳转到指定页面
location.reload() 重新加载页面

1577694035192

Pop-up box

可以在 JavaScript 中创建三种消息框:警告框、确认框、提示框。

Alert box

警告框经常用于确保用户可以得到某些信息。

当警告框出现后,用户需要点击确定按钮才能继续进行操作。

语法:
alert("你看到了吗?");

Confirmation box (to understand)

确认框用于使用户可以验证或者接受某些信息。

当确认框出现后,用户需要点击确定或者取消按钮才能继续进行操作。

如果用户点击确认,那么返回值为 true。如果用户点击取消,那么返回值为 false。

grammar:

confirm("你确定吗?")

Prompt box (to understand)

提示框经常用于提示用户在进入页面前输入某个值。

当提示框出现后,用户需要输入某个值,然后点击确认或取消按钮才能继续操纵。

如果用户点击确认,那么返回值为输入的值。如果用户点击取消,那么返回值为 null。

Column: Figure

1577694380413

grammar:

prompt("请在下方输入","你的答案")

Timing-related

通过使用 JavaScript,我们可以在一定时间间隔之后来执行代码,而不是在函数被调用后立即执行。我们称之为计时事件。

setTimeout()

grammar:

var t=setTimeout("JS语句",毫秒)
setTimeout() 方法会返回某个值。在上面的语句中,值被储存在名为 t 的变量中。假如你希望取消这个 setTimeout(),你可以使用这个变量名来指定它。

setTimeout() 的第一个参数是含有 JavaScript 语句的字符串。这个语句可能诸如 "alert('5 seconds!')",或者对函数的调用,诸如 alertMsg()"。

The second parameter indicates a parameter from the implementation of how many milliseconds from the current (1000 ms is equal to one).

clearTimeout()

grammar:

clearTimeout(setTimeout_variable)

For example :

// 在指定时间之后执行一次相应函数
var timer = setTimeout(function(){alert(123);}, 3000)
// 取消setTimeout设置
clearTimeout(timer);

1577695059979

setInterval()

setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。

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

grammar:

setInterval("JS语句",时间间隔)

return value

一个可以传递给 Window.clearInterval() 从而取消对 code 的周期性执行的值。

**clearInterval()**

clearInterval() 方法可取消由 setInterval() 设置的 timeout。

clearInterval() 方法的参数必须是由 setInterval() 返回的 ID 值。

grammar:

clearInterval(setinterval返回的ID值)

for example:

// 每隔一段时间就执行一次相应函数
var timer = setInterval(function(){console.log(123);}, 3000)
// 取消setInterval设置
clearInterval(timer);

1577695059979

JUDGMENT

DOM(Document Object Model)是一套对文档的内容进行抽象和概念化的方法。 

当网页被加载时,浏览器会创建页面的文档对象模型(Document Object Model)。

HTML DOM 模型被构造为对象的树。

HTML DOM tree

img

DOM standard specifies that each component of an HTML document is a node (node):

文档节点(document对象):代表整个文档
元素节点(element 对象):代表一个元素(标签)
文本节点(text对象):代表元素(标签)中的文本
属性节点(attribute对象):代表一个属性,元素(标签)才有属性
注释是注释节点(comment对象) 

JavaScript can create dynamic HTML through DOM:

JavaScript 能够改变页面中的所有 HTML 元素
JavaScript 能够改变页面中的所有 HTML 属性
JavaScript 能够改变页面中的所有 CSS 样式
JavaScript 能够对页面中的所有事件做出反应

Find label

Direct Find

document.getElementById           根据ID获取一个标签
document.getElementsByClassName   根据class属性获取
document.getElementsByTagName     根据标签名获取标签合集

1577695574238

Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>div</div>
<span class="c1">span</span>
<p id="d1">p</p>
</body>
</html>

note:

DOM operations related to the JS code should be placed in which position the document.

Indirect Find

parentElement            父节点标签元素
children                 所有子标签
firstElementChild        第一个子标签元素
lastElementChild         最后一个子标签元素
nextElementSibling       下一个兄弟标签元素
previousElementSibling   上一个兄弟标签元素

1577695588059

1577695605066

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <span>span上</span>
    <span>span上</span>
    <div class="c1">div
        <span>div>span</span>
        <p id="d1">div>p
            <span>
                div>p>span
            </span>
        </p>
        <span class="c2">div>span</span>
    </div>
    <span>span下</span>
    <span>span下</span>

</body>
</html>

Node operation

Creating nodes

grammar:

createElement(标签名)

Example:

var divEle = document.createElement("div");

1577695727235

Add Nodes

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div username="jason">div
    <span>div>span</span>
    <p>div>p</p>
</div>
</body>
</html>

grammar:

追加一个子节点(作为最后的子节点)

somenode.appendChild(newnode);

把增加的节点放到某个节点的前边。

somenode.insertBefore(newnode,某个节点);

1577695765155

Example:

var imgEle=document.createElement("img");
imgEle.setAttribute("src", "http://image11.m1905.cn/uploadfile/s2010/0205/20100205083613178.jpg");
var d1Ele = document.getElementById("d1");
d1Ele.appendChild(imgEle);

1577696861134

Delete node:

grammar:

获得要删除的元素,通过父元素调用该方法删除。

somenode.removeChild(要删除的节点)

Replace node:

grammar:

somenode.replaceChild(newnode, 某个节点);

Gets the value of the text node:

var divEle = document.getElementById("d1")
divEle.innerText
divEle.innerHTML

1577696717256

1577696749875

The text value of the node:

var divEle = document.getElementById("d1")
divEle.innerText="1"
divEle.innerHTML="<p>2</p>"

1577696682860

attribute operation

var divEle = document.getElementById("d1");
divEle.setAttribute("age","18")
divEle.getAttribute("age")
divEle.removeAttribute("age")

// 自带的属性还可以直接.属性名来获取和设置
imgEle.src
imgEle.src="..."

Gets the value of the operation

Code demonstrates

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text">

<!--<input type="radio" name='gender' value="male">-->
<!--<input type="radio" name='gender' value="female">-->
<!--<input type="radio" name='gender' value="others">-->

<select name="" id="">
    <option value="aaa">111</option>
    <option value="bbb">222</option>
    <option value="ccc">333</option>
</select>


<input type="file" id="d1">


</body>
</html>

Class attributes operation

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .c1 {
            height: 400px;
            width: 400px;
            border-radius: 50%;
        }
        .bg_green {
            background-color: green;
        }
        .bg_red {
            background-color: red;
        }
    </style>
</head>
<body>
<div class="c1 bg_green bg_red" ></div>
</body>
</html>

js operating label style

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>爱豆世纪骄傲的境况撒娇的空间三大</p>
</body>
</html>

grammar:

elementNode.value

For the following tags:

  • .input
  • .select
  • .textarea
var iEle = document.getElementById("i1");
console.log(iEle.value);
var sEle = document.getElementById("s1");
console.log(sEle.value);
var tEle = document.getElementById("t1");
console.log(tEle.value);

1577696640237

class action

className  获取所有样式类名(字符串)
classList.remove(cls)  删除指定类
classList.add(cls)  添加类classList.contains(cls)  存在返回true,否则返回falseclassList.toggle(cls)  存在就删除,否则添加

1577699500772

Specifies the CSS operation

obj.style.backgroundColor="red"

JS CSS property law operation:

1. For the CSS property not used directly in the horizontal line of the general style. Attribute name. Such as:

obj.style.margin
obj.style.width
obj.style.left
obj.style.position

2. CSS properties contained in the horizontal line, the first letter capitalized later horizontal line can be replaced. Such as:

obj.style.marginTop
obj.style.borderLeftWidth
obj.style.zIndex
obj.style.fontFamily

event

HTML 4.0 的新特性之一是有能力使 HTML 事件触发浏览器中的动作(action),比如当用户点击某个 HTML 元素时启动一段 JavaScript。下面是一个属性列表,这些属性可插入 HTML 标签来定义事件动作。

Common events

onclick        当用户点击某个对象时调用的事件句柄。
ondblclick     当用户双击某个对象时调用的事件句柄。

onfocus        元素获得焦点。               // 练习:输入框
onblur         元素失去焦点。               应用场景:用于表单验证,用户离开某个输入框时,代表已经输入完了,我们可以对它进行验证.
onchange       域的内容被改变。             应用场景:通常用于表单元素,当元素内容被改变时触发.(select联动)

onkeydown      某个键盘按键被按下。          应用场景: 当用户在最后一个输入框按下回车按键时,表单提交.
onkeypress     某个键盘按键被按下并松开。
onkeyup        某个键盘按键被松开。
onload         一张页面或一幅图像完成加载。
onmousedown    鼠标按钮被按下。
onmousemove    鼠标被移动。
onmouseout     鼠标从某元素移开。
onmouseover    鼠标移到某元素之上。

onselect      在文本框中的文本被选中时发生。
onsubmit      确认按钮被点击,使用的对象是form。

Binding way:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
<button onclick="func()">按钮1</button>
<button id="d1">按钮2</button>


<script>
        function func() {
        alert(123)
        }

        var btnEle = document.getElementById('d1');
        btnEle.onclick = function () {  // 给btn标签绑定一个点击事件  一旦被点击了 就会自动执行函数
            alert(456)
        }


</script>
</body>
</html>

method one:

<div id="d1" onclick="changeColor(this);">点我</div>
<script>
  function changeColor(ths) {
    ths.style.backgroundColor="green";
  }
</script>

note:

this is an argument that is the current element that triggered the event.

Function definition during ths as parameter.

Second way:

<div id="d2">点我</div>
<script>
  var divEle2 = document.getElementById("d2");
  divEle2.onclick=function () {
    this.innerText="呵呵";
  }
</script>

1577699637892

Event Exercise:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text" id="d1" value="你追我">


<script>
    var ipEle = document.getElementById('d1');
    ipEle.onfocus = function () {  // 获取焦点之后 将默认的文本内容清空
        ipEle.value = '';  // 不加参数就是获取 加了参数就是设置
    };
    ipEle.onblur = function () {  // 鼠标移出(失去焦点) 给input框再设置一个默认值
        ipEle.value = '下次记得再来看我哟~'
    }
</script>
</body>
</html>

Dynamic Display Time

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text" id="d1">
<button id="b1">开始</button>
<button id="b2">结束</button>


<script>
    var ipEle = document.getElementById('d1');
    var btn1Ele = document.getElementById('b1');
    var btn2Ele = document.getElementById('b2');
    // 先定义一个变量用来存储定时器
    var t = null;
    function showTime() {
        var currentTimeXXX = new Date();
        ipEle.value =  currentTimeXXX.toLocaleString();  // 转换成当地时间
    }

    // 开始按钮绑定事件
    btn1Ele.onclick = function () {
        if(!t){
             t = setInterval(showTime,1000);  // 每隔一秒钟执行一次
        }

    };
    // 结束按钮绑定事件
    btn2Ele.onclick = function () {
        clearInterval(t);  // 取消定时器
        // 还需要手动将t置位null
        t = null;
    }

</script>
</body>
</html>

Examples of events:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>开关灯示例</title>
    <style>
        .c1 {
            height: 400px;
            width: 400px;
            border-radius: 50%;
        }
        .bg_green {
            background-color: green;
        }
        .bg_red {
            background-color: red;
        }
    </style>
</head>
<body>
<div class="c1 bg_green bg_red"></div>
<button id="d1">点我变色</button>

<script>
    var btnEle = document.getElementById('d1');
    var divEle = document.getElementsByClassName('c1')[0];
    btnEle.onclick = function () {
        // console.log(this)  // 指代的是当前被操作对象本身
        divEle.classList.toggle('bg_red')
    }
</script>
</body>
</html>

Provinces linkage

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<select name="" id="province"></select>


<select name="" id="city"></select>

<script>
    data = {
        "河北": ["廊坊", "邯郸"],
        "北京": ["朝阳区", "海淀区"],
        "山东": ["威海市", "烟台市"],
        '上海': ['徐汇区','黄埔区'],
        '深圳': ['保安区','南山区']
    };
    let proEle = document.getElementById('province');
    let cityEle = document.getElementById('city');
    // 先获取一个个的省份信息
    for(let i in data){
        // 由于select标签中 一个个的选项就是一个个的option标签 所以我们需要自己手动创建该标签
        // 先创建一个option标签
        let opEle = document.createElement('option');
        // 给标签设置value属性
        opEle.value = i;
        // 给标签设置内部文本
        opEle.innerText = i;
        // 将创建好的option标签添加到select框中
        proEle.appendChild(opEle)
    }
    proEle.onchange = function () {  // 文本域改变自动触发
        // 先将第二个select框内容清空 再做添加操作
        cityEle.innerHTML = '';

        let currentPro = this.value;
        // 根据用户点击的省获取对应的市信息
        let currentCity = data[currentPro];
        // for循环市信息 动态创建option标签 一个个放入第二个select框中
        for(let i=0;i<currentCity.length;i++){
            let opEle = document.createElement('option');
            opEle.value = currentCity[i];
            opEle.innerText = currentCity[i];
            // 将创建好的option标签放入第二个select框中
            cityEle.appendChild(opEle)
        }
    }

</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<input type="text" id="i1">
<button id="b1">开始</button>
<button id="b2">结束</button>

<script>
    var t;
    function showTime() {
        var i1Ele = document.getElementById('i1');
        var time = new Date();
        i1Ele.value = time.toLocaleString();
    }
    showTime();
    var b1Ele = document.getElementById('b1');
    b1Ele.onclick = function (ev) {
        if (!t){
            t = setInterval(showTime,1000)
        }
    };
    var b2Ele = document.getElementById('b2');
    b2Ele.onclick = function (ev) {
       clearInterval(t);
       t = undefined
    };

</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>搜索框示例</title>

</head>
<body>
    <input id="d1" type="text" value="请输入关键字" onblur="blur()" onfocus="focus()">
    
<script>
function focus(){
    var inputEle=document.getElementById("d1");
    if (inputEle.value==="请输入关键字"){
        inputEle.value="";
    }
}

function blur(){
    var inputEle=document.getElementById("d1");
    var val=inputEle.value;
    if(!val.trim()){
        inputEle.value="请输入关键字";
    }
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>select联动</title>
</head>
<body>
<select id="province">
  <option>请选择省:</option>
</select>

<select id="city">
  <option>请选择市:</option>
</select>

<script>
  data = {"河北省": ["廊坊", "邯郸"], "北京": ["朝阳区", "海淀区"], "山东": ["威海市", "烟台市"]};

  var p = document.getElementById("province");
  var c = document.getElementById("city");

  for (var i in data) {
    var optionP = document.createElement("option");
    optionP.innerHTML = i;
    p.appendChild(optionP);
  }
  p.onchange = function () {
    var pro = (this.options[this.selectedIndex]).innerHTML;
    var citys = data[pro];
    // 清空option
    c.innerHTML = "";

    for (var i=0;i<citys.length;i++) {
      var option_city = document.createElement("option");
      option_city.innerHTML = citys[i];
      c.appendChild(option_city);
    }
  }
</script>
</body>
</html>

window.onload

When we bind events to elements on the page, you must wait until the document is loaded. Because we can not give binding element of a non-existent event.

window.onload event fires when the document load process ended. At this point, all objects in the document are located in the DOM, and all images, scripts, links, and sub-frames have finished loading.

Note: .onload () function exists to cover the phenomenon. '

Guess you like

Origin www.cnblogs.com/WQ577098649/p/12150141.html