[Part 5 | JS WebAPI] 2: DOM element operation

Table of contents

1-1 Change element content (remove html and space breaks)

1-2 Change the content of the element (retaining html and spaces are most used for newlines)

1-3 Get the content of the element

[ More other actionable element attributes ]

2-1 Modifying the attributes of an element

2-2 Modify form element attributes

2-3 Use this to point to the function caller

3-1 Operation through element.style style attribute

3-2 Batch modification of style attributes through element.className

4-1 Get the value inputElement.value input by the user

4-2 Case: Determine whether the password entered by the user meets the requirements

5-1 Get custom attributes

6-2 Setting the value of a custom property

6-3 Remove custom attributes

[ Summarize ]


Events: respond to certain operations on elements

Manipulating elements: DOM manipulation can change the content, structure and style of web pages. We can use DOM manipulation elements to change the content and attributes inside the elements. Note that the following are attributes

1-1 Change element content (remove html and space breaks)

content from the start position to the end position, but it strips html tags, while spaces and newlines also go

element.innerText = 'XXXXXX';
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="id">猜猜我是谁</div>
    <button id="btn">Guess</button>
    <script>
        //获取元素
        var id = document.getElementById('id');
        var btn = document.getElementById('btn');

        //绑定事件、函数
        btn.onclick = function(){
            id.innerText = '我是Klee';
        }
        
    </script>
</body>
</html>
 

1-2 Change the content of the element (retaining html and spaces are most used for newlines)

  • innerText does not recognize html tags, it will be kept and displayed without line breaks and spaces

  • innerText is initiated by IE itself, and Firefox does not support it; innerHTML is recommended by W3C and is used the most.

element.innerHTML = 'XXXXX';

1-3 Get the content of the element

  • element.innerText and element.innerHTML can not only modify the element content, but also read the element content.

  • The difference is: XXXX = element.innerXXX represents acquisition; element.innerXXX = XXX represents modification


[ More other actionable element attributes ]

Basic usage:

get element → bind event → declare function → element.property = value to be modified

2-1 Modifying the attributes of an element

For example, img src="XXXX", we can actually modify paths such as src through the operation of elements

    <!-- 改变元素属性 -->
    <img src="imgs/p1.jpg" id="img" style="width: 400px;height: 600px;">
    <button id="changeP">换图片</button>
    <script>
        //获取元素
        var img = document.getElementById('img');
        var change = document.getElementById('changeP');
        //绑定事件、函数
        change.onclick = function(){
            //修改img的src属性,更换图片
            img.src = 'imgs/p2.jpg';
        }
    </script>

 


2-2 Modify form element attributes

Case: Click the small eyes to change the password to plain text display

    <!-- 操作表单元素:点击小眼睛可以明文密码 -->
    <input type="password" placeholder="input pwd" name="pass" id="pass">
    <button id="eye">eye</button>
    <script>
        //获取元素
        var pass = document.getElementById('pass');
        var eye = document.getElementById('eye');
        //绑定事件、函数
        eye.onclick = function(){
            pass.type = 'text';
        }
    </script>

 Case 2: After the button is clicked, no further clicks are given

 


2-3 Use this to point to the function caller

  • btn.disabled = true; can be rewritten as this.disabled = true; the effect is the same

  • this points to the function caller.


3-1 Operation through element.style style attribute

We can modify the size, color, position and other styles of elements through JS

 

The element.style syntax can only modify one property at a time. If you need to modify attributes in batches, it is recommended to use the className syntax, which will be learned later

 

code example

    <!-- 样式属性操作 -->
    <div class="b" style="width: 100px;height: 100px; background-color: pink;"></div>
    <button id="changeStyle">换皮肤</button>
    <script>
        //获取元素
        var b = document.getElementsByClassName('b'); //这个获取的是一个元素对象集合!需要 b[0] 取出元素对象
        var block = b[0];
        var changeStyle = document.getElementById('changeStyle');
        //绑定事件和函数
        changeStyle.onclick = function(){
            block.style.backgroundColor = 'blue';//JS的属性名字是驼峰命名法
        }        
    </script>

 Case: Taobao two-dimensional code click to hide (idea: click the button to hide the element)

 Case: Loop sprite map

Case: Sina drop-down menu

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        li {
            list-style: none;
        }

        .nav {
            position: relative;

            width: 100%;
            height: 60px;
            background-color: lightblue;
        }

        .nav .box1 {
            width: 100px;
            height: 100%;
            
            color: black;
            font-size: 20px;
            font-weight: 600;
            text-align: center;
            line-height: 60px;
        }

        .nav .box1:hover {
            background-color: lightslategray;
        }

        .nav .box1content {
            position: absolute;
            left: 0;
            top: 60px;

            width: 100px;
            height: 100px;
            background-color: pink;

            visibility: hidden;
        }
    </style>
</head>
<body>
    <div class="nav">
        <div class="box1">下拉菜单</div>
        <div class="box1content">
            <li>1</li>
            <li>2</li>
            <li>3</li>
        </div>
    </div>

    <script>
        var box1 = document.querySelector('.nav .box1');
        var content1 = document.querySelector('.nav .box1content');

        box1.onmouseover = function(){
            content1.style.visibility = 'visible';
        }
        box1.onmouseout = function(){
            content1.style.visibility = 'hidden';
        }
        content1.onmouseover = function(){
            content1.style.visibility = 'visible';
        }
        content1.onmouseout = function(){
            content1.style.visibility = 'hidden';
        }

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

 


3-2 Batch modification of style attributes through element.className

basic grammar

<style>
	.classname {
		//属性
	}
</style>

<script>
	var element = document.getXXXX; 
	element.className = 'classname';
</script>


Precautions

  • If there are many style modifications, you can change the element style by manipulating the class name.

  • The new css class name style assigned by element.className will overwrite the CSS style class name used by the original element

  • If you want to keep the original CSS style class name, you can write element.className = 'Original class name and new style class name';

code example

<!DOCTYPE html>
<html lang="en
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 200px;
            height: 200px;
            margin: 100px auto;
            background-color:  pink;
        }

        .boxchange {
            width: 300px;
            height: 300px;
            margin: 90px auto;
            background-color: greenyellow;
        }
    </style>
</head>
<body>
    <div class="box"></div>
    <button id="btn">Click</button>
    <script>
        var box = document.getElementsByClassName('box');
        var boxObj = box[0];//通过className获取的是元素对象集合,需要通过下标取出元素对象
        var btn = document.getElementById('btn');
        btn.onclick = function(){
            boxObj.className = 'boxchange';//注意,这里的CSS类名不需要加 “ . ”
        }
        
    </script>
</body>
</html>

4-1 Get the value inputElement.value input by the user

//input表单元素的元素对象是i的话,则获取用户输入的内容的语法是

var XXX = i.value;

Case: The format of the password box prompts an error message

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* CSS样式 */
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            width: 700px;
            height: 100px;
            margin: 200px auto;
            background-color: antiquewhite;
        }

        .box .put {
            width: 100%;
            height: 50px;
        }

        .box .put input {
            display: block;
            float: left;
            margin: 10px;
            width: 300px;
            height: 20px;
        }

        .box .put .tips {
            float: left;

            margin: 12px;
            height: 20px;
            width: 300px;
            border: red;

            line-height: 20px;
            color: red;
            font-weight: 600;
            font-family: 'Microsoft YaHei';

            visibility: hidden;
        }


        .box button {
            margin: 10px;
            display: block;
            float: left;
        }
    </style>
</head>
<body>
    <!-- 基本结构 -->
    <div class="box">
        <div class="put">
            <input type="password" placeholder="设置密码" name="pwd" value="">
            <div class="tips">X 格式不符合要求!需要6位,且含大小写</div>
        </div>
        <button>设置</button>
    </div>

    <!-- JS逻辑判断 -->
    <script>
        var btn = document.querySelector('.box button');
        var pwd = document.querySelector('.box .put input');
        var tip = document.querySelector('.box .put .tips');

        btn.onclick = function(){
            var pwdStr = pwd.value;//通过input的value获取用户输入
            console.log(pwdStr);
            if(pwdStr.length < 6) {
                tip.style.visibility = 'visible';
            }
            else {
                tip.style.visibility = 'hidden';
                alert('注册成功');
            }
        }

    </script>

</body>
</html>

 

Way 2: When the cursor leaves, an event is triggered. input.onblur


4-2 Case: Determine whether the password entered by the user meets the requirements

Characters in JS cannot be used directly as ASCII codes! need to convert

char → ASCII

 let x = 'a';
 x.charCodeAt(); //会输出'a'的ASCII码,即97

ASCII → char

String.fromCharCode(97); //会输出ASCII码为97的字符,即'a'

Sample code: If the password entered by the user is less than 6 characters and does not contain uppercase and lowercase, it will prompt that it is unqualified

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* CSS样式 */
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            width: 700px;
            height: 100px;
            margin: 200px auto;
            background-color: antiquewhite;
        }

        .box .put {
            width: 100%;
            height: 50px;
        }

        .box .put input {
            display: block;
            float: left;
            margin: 10px;
            width: 300px;
            height: 20px;
        }

        .box .put .tips {
            float: left;

            margin: 12px;
            height: 20px;
            width: 300px;
            border: red;

            line-height: 20px;
            color: red;
            font-weight: 600;
            font-family: 'Microsoft YaHei';

            visibility: hidden;
        }


        .box button {
            margin: 10px;
            display: block;
            float: left;
        }
    </style>
</head>
<body>
    <!-- 基本结构 -->
    <div class="box">
        <div class="put">
            <input type="password" placeholder="设置密码" name="pwd" value="">
            <div class="tips">X 格式不符合要求!需要6位及以上,且含大小写</div>
        </div>
        <button>设置</button>
    </div>

    <!-- JS逻辑判断 -->
    <script>
        var btn = document.querySelector('.box button');
        var pwd = document.querySelector('.box .put input');
        var tip = document.querySelector('.box .put .tips');

        btn.onclick = function(){
            var pwdStr = pwd.value;//通过input的value获取用户输入
            console.log(pwdStr);

            if(pwdStr.length < 6 || !haveBigOrSmall(pwdStr)) {
                tip.style.visibility = 'visible';
            }
            else {
                tip.style.visibility = 'hidden';
                alert('注册成功');
            }
        }

        function haveBigOrSmall(str){
            var len = str.length;
            var small = false;
            var big = false;

            for(var i=0 ; i<len ; i++){

                if(big && small){
                    return true;
                }

                if( str.charCodeAt(i) >= 65 && str.charCodeAt(i) <= 90 && big!=true ){
                    big = true;
                }
                if( str.charCodeAt(i) >= 97 && str.charCodeAt(i) <= 122 && small!=true ){
                    small = true;
                }
            }
            return false;
        }


    </script>

</body>
</html>

5-1 Get custom attributes

What are custom attributes?

  • Non-built-in attributes written in tags are considered custom attributes

  • Custom attribute purpose: to save and use data. Some data can be saved to the page without saving to the database.

  • Such as the index of the column. It is not a built-in attribute of Html, but it will not compile an error (after all, Html is a text language), but will regard index as a programmer-defined attribute

 

<div index="1"></div>

How to obtain custom attributes?

元素对象.getAttribute('属性名字');
  • It should be noted that the acquisition syntax of custom attributes can also be applied to built-in element attributes (such as style, src, title, etc.)

the difference


6-2 Setting the value of a custom property

It is worth noting that if there is no corresponding custom attribute in the tag name, this attribute will be added automatically when using setAttribute

 

code example  

<div index="2"></div>
<script>
	var div = document.getElementByTagName('div'); //获取dom元素对象
	div.setAttribute('index','2'); //设置对象中的自定义属性的值为2
</script>

6-3 Remove custom attributes

element.removeAttribute('属性');

[ Summarize ]

Guess you like

Origin blog.csdn.net/m0_57265007/article/details/127981215