BOM and DOM operations of the front end js

Introduced

JavaScript is divided into ECMAScript, DOM, BOM.

BOM (Browser Object Model) refers to the browser object model that enables JavaScript capable browser to "talk."

DOM (Document Object Model) refers to the document object model, through which you can access all the elements of the HTML document.

BOM operation

window object

Window object is one of the top target client JavaScript, because the window object is the common ancestor of most of the other objects, when calling window object's methods and properties, you can omit a reference to the window object. For example: window.document.write () can be abbreviated as: document.write ().

All browsers support the window object. It represents the browser window.
Global variables are window object's properties. Global function is the window object.

Some commonly used Window methods:

  • Internal height of the browser window - window.innerHeight
  • window.innerWidth - inside the browser window width
  • window.open () - opens a new window
  • window.close () - Close the current window

history objects

history.back() #回退,类似于浏览器左上角的左箭头;
history.forWord() # 前进,类似于浏览器左上角的右箭头;

The location object (focus)

window.location object is used to get the address (URL) of the current page, and the browser is redirected to the new page.

Common attributes and methods:

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

Pop-up box

JavaScript can create three kinds of message boxes: warning box (alert), confirmation box (confirm), prompt box (prompt).

Alert box

Alert box is often used to ensure that users can get some information.

When the warning box appears, users need to click the OK button in order to proceed.

grammar:

alert("你看到了吗?");

Confirmation box (to understand)

Check box for the user to verify or receive certain information.

When the confirmation box appears, users need to click OK or Cancel button in order to proceed.

If the user clicks to confirm, the return value is true. If the user clicks Cancel, the returned value is false.

grammar:

confirm("你确定吗?")

Prompt box (to understand)

Prompt box is often used to prompt the user to input a value before entering a page.

When the prompt box appears, users need to enter a value, then click OK or Cancel button to continue to manipulate.

If the user clicks to confirm, the return value is entered. If the user clicks Cancel, the returned value is null.

grammar:

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

Timer

setTimeout()

By using JavaScript, we can in a certain interval of time later to execute code, and not immediately after the function is called. We call timed events.

clearTimeout()

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    function func() {
        alert('都是废话!!')
    }
    function show() {
        let t = setTimeout(func,3000);  // 设置定时器,每个3s执行一次func函数
        function inner() {
            clearTimeout(t)  // 清除定时器
        }
        setTimeout(inner,9000) // 设置9s后执行inner函数(内层函数)
    }
    show()
</script>
</body>
</html>

Timer-related

setInterval () # pop up every once in a

setInterval () method in accordance with a specified period (in milliseconds) to the calling function or calculation expression. setInterval () method will continue to call the function, until the clearInterval () is called, or the window is closed. A setInterval () ID is used as a parameter value returns the clearInterval () method.

clearInterval()

the clearInterval () method cancels the timeout setInterval () set.

The clearInterval parameter () method must be the ID value of setInterval () returns.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    function func() {
        alert(123)
    }
    function show() {
        var t=setInterval(func,3000);  // 设置定时器每隔3s触发一次func函数
        function inner() {
            clearInterval(t)
        }
        setTimeout(inner,9000)
    }
    show()
</script>
</body>
</html>

JUDGMENT

DOM (Document Object Model) is a set of methods for the content of the document and abstract conceptualization.
When the page is loaded, the browser will create a page of a document object model (Document Object Model).
HTML DOM model is constructed as an object tree.

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

  • Document node (document object): On behalf of the entire document
  • Element node (element object): represents an element (tag)
  • Node text (text object): Representative elements (tags) in the text
  • Node attribute (attribute objects): represents an attribute element (tag) have properties
  • Comments are comment nodes (comment Object) 

JavaScript can create dynamic HTML through DOM:

  • JavaScript can change all the HTML elements on the page
  • JavaScript can change the properties of all HTML pages
  • JavaScript can change all CSS styles page
  • JavaScript can react to all events page

Find label

Direct Find

document.getElementById           根据ID获取一个标签
document.getElementsByClassName   根据class属性获取
document.getElementsByTagName     根据标签名获取标签合集
<!--浏览器运行该HTML文件,在console内查找标签-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<span>div上面的span</span>

<div>我是div
    <span>div里面的第一个span</span>
    <p>div里面的span下面的p标签
        <span>div里面的p里面的span标签</span>
            
    </p>
    <span>div里面的p下面的span标签</span>
    
</div>
<span>div下面的span标签</span>
</body>
</html>

Indirect Find

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


Node operation

<!--图片文件-->
1.png
<!--HTML文件-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<span id="s1" class="c1">div上面的span</span>
<div id="d1" class="c2">我是div
    <p>div>p</p>
    <span>div>span</span>
    <p id="p1">div>p:
        <span id ="s3">div>p>span</span>
    </p>
</div>
<span>div+span</span>
</body>
</html>

Create a node and add nodes


Tag is inserted at the specified location

Delete Node

grammar:

Gets the element you want to delete, delete the method by calling the parent element.

somenode.removeChild (node ​​to be removed)

Replacement Node

grammar:

somenode.replaceChild (newnode, a node);

Attribute nodes and text nodes

Gets the value of the text node:

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

The text value of the node:

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

setattribute

Either create own label, you can also create custom attributes

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

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);

Example:

1)input

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

<textarea name="" id="t1" cols="30" rows="10"></textarea>
</body>
</html>

2)select

3)textarea

Label class (class) properties

className  获取所有样式类名(字符串)

classList.remove(cls)  删除指定类
classList.add(cls)  添加类
classList.contains(cls)  存在返回true,否则返回false
classList.toggle(cls)  存在就删除,否则添加
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .c1 {
            width: 200px;
            height: 200px;
            border-radius:50%;
            border: 3px solid black;
        }
        .bg_red {
            background-color: red;
        }
        .bg_green {
            background-color: green;
        }
    </style>
</head>
<body>
<div class="c1 bg_red bg_green"></div>
</body>
</html>

Label style 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

One of the new features of HTML 4.0 is the ability to make HTML browser event triggers the action (action), like starting a JavaScript when a user clicks on an HTML element. The following is a list of attributes that can be inserted into the HTML tags to define event actions.

Common Time

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

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

onkeydown      某个键盘按键被按下。          应用场景: 当用户在最后一个输入框按下回车按键时,表单提交.
onkeypress     某个键盘按键被按下并松开。
onkeyup        某个键盘按键被松开。

onload         一张页面或一幅图像完成加载。

onmousedown    鼠标按钮被按下。
onmousemove    鼠标被移动。
onmouseout     鼠标从某元素移开。
onmouseover    鼠标移到某元素之上。

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

Way binding events

The user clicks a button, it will trigger an action generated HTML page, this button is bound to this event.

Js the writing position code:

js code when writing, make sure to perform a normal html file after the page is fully loaded, otherwise an error. Two solutions.

1.window.onload = function (which is written js code) title internal label
, such as:
the window.onload = function () {
var Bele = document.getElementById ( 'B');
};

* 2.js internal script code in the bottom of the innermost HTML document body

1) Click event

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

</head>
<body>
<button onclick="func()">按钮</button>
<input type="button" value="按钮2" id="d1">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>10</p>
 <script>
        function func() {
            alert ('我被点击了!')
        }
        var inEle = document.getElementById('d1');
        inEle.onclick = function(){
            // inEle标签被点击之后我们能在这里添加的功能
            func()
        };
        var pEle = document.getElementsByTagName('p')[0];
        pEle.onclick = function () {
            alert('p标签被点击了!')
        }
 </script>
</body>
</html>

2) Example light switch

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .c1 {
            height: 200px;
            width: 200px;
            border-radius: 50%;
        }
        // 背景色顺序要多多留意,如果没效果,要上下调换一下;
        .bg_green {
            background-color: green;
        }
        .bg_red {
            background-color: red;
        }
    </style>
</head>
<body>
<div class="c1 bg_red bg_green"></div>
<button id="d1">变色</button>

<script>
    var bEle = document.getElementById('d1');
    bEle.onclick = function() {
        // 找到div标签
        var divEle = document.getElementsByClassName('c1')[0];
        // 修改类属性 有则删除,无则添加;
        divEle.classList.toggle('bg_red')
    }
</script>
</body>
</html>

3) input box acquired focus example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text" value="精品按摩198一位" id="d1">
<!--// placeholder 是设置input框里的默认文本,当从新输入时,默认文本会清除。-->
<!--<input type="text" placeholder="全套服务仅需888" id="d1">-->

<script>
    var iEle = document.getElementById('d1');
    // input获取焦点
    iEle.onfocus = function () {
        // 将input框中的文本值清除
        iEle.value = ''
    };
    // input框失去焦点
    iEle.onblur = function () {
        iEle.value = '欢迎老板下次光临~'
    }
</script>
</body>
</html>

4) shows the current time event

<!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 t = null;
    var b1Ele = document.getElementById('b1');
    var b2Ele = document.getElementById('b2');
    var iEle = document.getElementById('d1');
    function showTime() {
        var currentTime = new Date();
        var ctime = currentTime.toLocaleString();
        iEle.value = ctime
    }
    // 开始按钮
    b1Ele.onclick = function () {
        if(!t){
             t = setInterval(showTime,1000)
        }
    };
    // 结束
    b2Ele.onclick = function () {
        clearInterval(t);
        // 手动将t清空
        t = null
    }
</script>

</body>
</html>

5) provinces linkage

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<select name="" id="d1">省:</select>
<select name="" id="d2">市:</select>

<script>
    var s1Ele = document.getElementById('d1');
    var s2Ele = document.getElementById('d2');


    var data = {
        "河北省": ["廊坊", "邯郸",'石家庄'],
        "北京": ["朝阳区", "海淀区",'昌平区'],
        "山东": ["威海市", "烟台市",'青岛'],
        "上海":["静安区",'黄浦区','徐汇区']
    };
    // 循环自定义对象中的key 动态创建option标签 添加到第一个选择框中
    for (let province in data){
        // 创建一个个的option标签
        var optEle = document.createElement('option');
        // 给创建的option标签设置文本和属性
        optEle.innerText = province;
        optEle.value = province;
        // 将创建好的option标签添加到select框中
        s1Ele.appendChild(optEle)
    }
    s1Ele.onchange = function () {
        // console.log(this.value)  // this指代的就是当前操作对象本身  有点类似于你python后端的self
        // 获取用户选择的省 根据省 取到对应的市
        var currentPro = this.value;
        var cityList = data[currentPro];

        // 先将第二个select框中的所有内容清空
        s2Ele.innerHTML = '';
        // 循环市的数组 创建option标签  操作属性  添加到第二个select框中
        for (let i=0;i<cityList.length;i++){
            var optEle = document.createElement('option');
            optEle.innerText = cityList[i];
            optEle.value = cityList[i];
            s2Ele.appendChild(optEle)
        }
    }
</script>
</body>
</html>

Guess you like

Origin www.cnblogs.com/zhangchaocoming/p/11886650.html