zoukankan      html  css  js  c++  java
  • 第十一章 前端开发-JavaScript

    第十一章 前端开发-JavaScript

    11.3.1 js引入方式

    1. 行内样式

      <p id="" class="" style="" onclick="console.log(2);">mjj</p>
      
    2. 内嵌式

      <script type="text/javascript">
          // js代码
      </script>
      
    3. 外接式

      <script type="text/javascript" src="js/index.js"></script>
      

    11.3.2 js基础语法

    11.3.2.1 测试语句

    1. 打印:console.log();

    2. 弹出框:alert();

    3. 输入:prompt(message:'请输入');

      • 有返回值,使用变量接收
    4. 示例:

      console.log('hello world');
      alert('hello world');
      console.log(window);
      var name = prompt('请输入今天的天气?');
      console.log(name);
      
    5. 注释

      //单行注释
      /*多
      行
      注
      释*/
      ...
      
    6. 运算符

      • a ++;相当于 a+=1;
      • ++ a;相当于 a+=1;
      var a = 1;
      a ++;      // 相当于 a+=1;
      ++ a;      // 相当于 a+=1;
      
      var a = 4;
      // 先把a的值赋值给c,再a++
      var c = a ++;
      console.log(c);   // 4
      console.log(a);   // 5
      // 先++a,再赋值给c
      var c = ++a;
      console.log(c);   // 5
      console.log(a);   // 5
      
    7. (等于)和=(等同于)的区别

      var a = 2;
      var b = '2';
      console.log(a == b);      // 比较的是值,为true
      console.log(a === b);     // 比较是值和数据类型,为false
      

    11.3.2.2 变量

    1. 基本数据类型

      • 整型:number
      • 字符串:string
      • 布尔:boolean
      • 未定义的:undefined
      • 空对象:null
      var a = 2;      // 整型
      var b = '2';    // 字符串
      var c = true;   // 布尔
      var d;          // 未定义的
      var e = null;   // 空对象
      
      // 先声明后定义
      var f;
      console.log(f);   // 值  是undefined
      console.log(typeof f);  // 类型  是undefined
      
    2. 引用数据类型

      • 数组:Array
      • 对象:Object
      • 函数:function
    • 时间:Date

      var arr = ['张三','李四'];   //数组
      
      // js中,有全局作用域和函数作用域
      // 1.普通函数的声明
      function add(a,b){
          return a + b
      }
      // 2.函数表达式
      var add2 = function(){
      };
      // 3.自执行函数
      ;(function(){
          alert(1111);
      })();
      
      // 定义在对象中的函数,叫做对象的方法
      var obj = {
          name:'mjj',
          age:19,
          fav:function () {
              console.log(this);
          }
      };
      obj.fav();
      
    1. 其他:NaN(不是数字),Infinity(无限大)

      • NaN:不是一个数字,不是整型
        • isNaN:判断是否是NaN
      • 对于运算来说,Infinity相当于报错
    2. 函数:解决冗余性的代码,为了封装

      • 定义函数
      function sum(a,b){
          // 函数体;
      }
      
      • 函数调用
      function sum(a,b){
          console.log(a+b);
      }
      sum(3,5);    // 调用函数,直接写函数名
      
      • 函数返回值
      function sum(a,b){
          return a+b
      }
      var result = sum(4,5);
      
      • 函数的arguments:伪数组
      function  fn(a,b) {
          // arguments.length,是实参的个数
          // arguments它不是一个数组,它被称为叫伪数组
          console.log(arguments);
          for(var i = 0; i < arguments.length; i++){
              console.log(arguments[i]);
          }
      }
      fn(2,3,4);
      console.log(fn.length);		// fn.length,是形参的个数
      

    11.3.2.3 流程控制

    1. if语句

      var score = 100;
      if(score > 80){
          console.log('可以吃鸡了');
      }else if(score > 70) {
          console.log('在家呆着');
      }else{
          console.log('学习');
      }
      
      // 特殊:三元运算
      var a =  1 < 2 ? "yes": "no";
      console.log(a);
      
    2. switch语句

      var weather = prompt('请输入今天的天气');
      switch (weather) {
          case '晴天':
              console.log('可以去打篮球');
              break;
          case '下雨':
              console.log('可以睡觉');
              break;
          default:
              console.log('学习');
              break;
      }
      

    11.3.2.4 循环

    1. for循环

      var arr = [8,9,0];
      // 1.初始化循环变量  2.循环条件  3.更新循环变量
      for(var i = 0;i < arr.length; i++){
          console.log(arr[i]);
      }
      
    2. while循环

      初始化条件
      while(判断循环结束条件){
          // code to run
          递增条件
      }
      
      // 打印1到100之间的数
      var a = 1;
      while(a <= 100){
          console.log(a);
          a+=1;
      }
      

    11.3.3 js常用对象

    11.3.3.1 对象

    1. 创建对象

      • 构造函数
        • 使用new操作符后跟Object构造函数
      // 创建对象
      var person = new Object();
      // 给对象添加name和age属性
      person.name = 'jack';
      person.age = 28;
      // 给对象添加fav的方法
      person.fav = function(){
          console.log('泡妹子');
      }
      
      // 特殊:
      var person = {};    // 与new Object()相同
      
      • 使用对象字面量表示法
        • 对象字面量是对象定义的一种简写形式,目的在于简化创建包含大量属性的对象的过程
      var person = {
          name : 'jack';
          age : 28,
          fav : function(){
              console.log('泡妹子');
          }
      }
      
      • this指向
        • 对象中的this指向当前对象
        • 全局作用域中的this,一定指向window
        • 函数中的this,一般情况下,都指向window
          • 特殊情况:使用call和apply,此时this指向传入的对象
        • 自执行函数中的this,一定指向window
      var obj = {};
      obj.name = 'mjj';
      obj.fav = function(){		
          console.log(this);		// 此时this指向当前对象,即obj 
      }
      
      console.log(this);			// 此时this指向window
      function  add(x,y) {
          console.log(this.name);
      }
      add();					   // 空值,此时this指向window
      add.call(obj,1,2);		    // 此时this指向传入的对象,即obj
      add.apply(obj,[1,2]);		// 此时this指向传入的对象,即obj
      
      (function () {
          console.log(this);		// 此时this指向window
      })()
      
    2. 访问对象中属性的方法

      • 点语法:用来访问对象中的属性
      person.name;    		// jack
      person.fav();   		// 泡妹子
      
      • 括号表示法
      person['name'];  		// 相当于person.name;
      
    3. 遍历对象

      var obj = {};
      for (var key in obj){
          obj[key]
      }
      
    4. 面向对象

      // 使用构造函数来创建对象
      function Point(x, y) {
        this.x = x;
        this.y = y;
      }
      Point.prototype.toString = function () {
        return '(' + this.x + ', ' + this.y + ')';
      };
      var p = new Point(1, 2);
      
      // es6用class来创建对象
      class Person{
          constructor(name,age){
              // 初始化
              this.name = name;
              this.age = age;
          }
          fav(){
              console.log(this.name);
          }
      }
      var p = new Person('mjj',18);
      p.fav();
      

    11.3.3.2 数组:Array

    1. 数组的创建方式

      • 跟object创建对象一样,使用Array构造函数方式创建
      var colors = new Array();
      
      
      • 使用字面量方式创建数组
      var colors = [];
      
      
    2. Array.isArray():确定某个值到底是否是数组

      var colors = ['red','green','blue'];
      Array.isArray(colors);      	// true
      
    3. toString():返回由数组中每个值以一个以逗号拼接成的字符串

      var colors = ['red','green','blue'];
      alert(colors.toString());    	// red,green,blue
      
    4. join方法:返回由数组中每个值以相同符号拼接成的字符串

      var colors = ['red','blue','green'];
      colors.join('||');          	// red||blue||green
      
    5. 栈方法:LIFO(后进先出)

      • push():进,可以接收任意数量的参数,把它们逐个添加到数组末尾,并返回修改后数组的长度
      var colors = [];
      var count = colors.push('red','blue','green');
      alert(count);      			// 3
      
      • pop():出,从数组末尾移除最后一项,减少数组的length值,然后返回移除的项
      var item = colors.pop();     // 取最后一项
      alert(item); 			    // green
      alert(colors.length);        // 2
      
    6. 队列方法:FIFO(先进先出)

      • unshift():进,在数组前端添加任意个项并返回新数组的长度
      var colors = [];
      var count  = colors.unshift('red','green');  // 推入两项
      alert(count); 		    	// 2
      console.log(colors);     	// ["red", "green"]
      
      • shift():出,移除数组中的第一个项并返回该项,同时将数组长度减1
      var colors = ['red','blue','green'];
      var item = colors.shift();       // 取得第一项
      alert(item); 		    	// "red"
      alert(colors.length);    	// 2
      
      
    7. 重排序方法

      • reverse():反转,翻转数组项的顺序
      var values = [1,2,3,4,5];
      values.reverse();
      alert(values); 			// 5,4,3,2,1
      
      
      • sort():排序,默认是升序排列
      // 升序
      function compare(v1,v2){
          if(v1 < v2){
              return -1;
          }else if (v1 > v2){
              return 1;
          }else{
              return 0;
          }
      }
      var values = [0,1,5,10,15];
      values.sort(compare);
      alert(values);           // 0,1,5,10,15
      // 降序
      function compare(v1,v2){
          if(v1 < v2){
              return 1;
          }else if (v1 > v2){
              return -1;
          }else{
              return 0;
          }
      }
      var values = [0, 1, 5, 10, 15];
      values.sort(compare);
      alert(values);    		// 15,10,5,1,0
      
      
    8. 操作方法

      • concat():数组合并方法,一个数组调用concat()方法去合并另一个数组,返回一个新的数组,接收的参数是可以是任意的
        • 参数为一个或多个数组,会将这些数组中每一项都添加到结果数组中。
        • 参数不是数组,这些值就会被简单地添加到结果数组的末尾
      var colors = ['red','blue','green'];
      colors.concat('yello');           		 // ["red", "blue", "green", "yello"]
      colors.concat({'name':'张三'});           // ["red", "blue", "green", {…}]
      colors.concat({'name':'李四'},['black','brown']);  
      // ["red", "blue", "green", {…}, "black", "brown"]
      
      
      • slice():基于当前数组中一个或多个项创建一个新数组,可以接受一或两个参数,要返回项的起始和结束位置
        • 一个参数的情况下,返回从该参数指定位置开始到当前数组默认的所有项
        • 两个参数的情况下,返回起始和结束位置之间的项,但不包括结束位置的项
      var colors = ['red','blue','green','yellow','purple'];
      // 正值情况下
      colors.slice(1);	    // ["blue", "green", "yellow", "purple"]
      colors.slice(1,4);      // ["blue", "green", "yellow"]
      // 负值情况下
      colors.slice(-2,-1);	// ["yellow"] 
      colors.slice(-1,-2);	// []
      
      
      • splice():给数组插入、删除、替换项
        • 插入:向指定位置插入任意数量的项,只需提供3个参数:起始位置,0(要删除的个数),要插入的项
        • 删除:删除任意数量的项,只需指定2个参数:要删除的第一项的位置,要删除的个数
        • 替换:向指定位置插入任意数量的项,且同时删除任意数量的项,只需指定 3 个参数:起始位置,要删除的项数,要插入的任意数量的项
      var colors = ["red", "green", "blue"];
      var removed = colors.splice(0,1); 
      alert(colors); 		// green,blue 
      alert(removed); 	// red,返回的数组中只包含一项
      removed = colors.splice(1, 0, "yellow", "orange"); 
      alert(colors); 		// green,yellow,orange,blue 
      alert(removed); 	// 返回的是一个空数组
      removed = colors.splice(1, 1, "red", "purple"); 
      alert(colors); 		// green,red,purple,orange,blue 
      alert(removed); 	// yellow,返回的数组中只包含一项
      
      
    9. 位置方法

      • indexOf():从数组的开头(索引位置0)开始向后查找
      • lastIndexOf():从数组的末尾开始向前查找,然后然会他的索引
      var numbers = [1,2,3,4,5,4,3,2,1];
      numbers.indexOf(4);		    // 3
      numbers.lastIndexOf(4);		// 5  
      numbers.indexOf(4,4);		// 5
      numbers.lastIndexOf(4,4);	// 3
      var person = {name:"mjj"};
      var people = [{name:'mjj'}];
      var morePeople = [person];
      people.indexOf(person); 	 // -1
      morePeople.indexOf(person);  // 0
      
    10. 迭代方法

      • filter():利用指定的函数确定是否在返回的数组中包含某一项
      var numbers = [1,2,3,4,5,4,3,2,1];
      var filterResult = numbers.filter(function(item, index, array){
          return (item > 2);
      });
      alert(filterResult); 	// [3,4,5,4,3]
      
      
      • map():返回一个数组,而这个数组的每一项都是在原始数组中的对应项上执行函数的结果
      var numbers = [1,2,3,4,5,4,3,2,1];
      var filterResult = numbers.map(function(item, index, array){
          return item * 2;
      });
      alert(filterResult); 	// [2,4,6,8,10,8,6,4,2]
      
      
      • forEach():对数组中的每一项执行函数,没有返回值,本质上与使用for循环迭代数组一样,只能在数组中使用
      //执行某些操作,相当于for循环
      var numbers = [1,2,3,4,5,4,3,2,1];
      numbers.forEach(function(item, index, array){
      });
      

    11.3.3.3 字符串:String

    1. 字符串的创建方式

      var stringValue = "hello world"; 
      
      
    2. length属性

      var stringValue = "hello world"; 
      alert(stringValue.length);            // "11"
      
      
    3. 字符方法

      • charAt():返回给定位置的那个字符
      var stringValue = "hello world"; 
      alert(stringValue.charAt(1));         // "e"
      
      
      • charCodeAt():返回给定位置的那个字符所对应的编码
      var stringValue = "hello world";
      alert(stringValue.charCodeAt(1));     // 输出"101"
      
      
    4. 字符操作方法

      • concat():用于将一或多个字符串拼接起来,返回拼接得到的新字符串
      • +或${},也可以拼接字符串
      • es6的模板字符串,使用``(Tab上面的那个键)
      var stringValue = "hello ";
      var result = stringValue.concat("world"); alert(result);           // "hello world" 
      alert(stringValue);      // "hello"
      
      // concat()方法可以接受任意多个参数,也就是说可以通过它来拼接任意多个字符串
      var stringValue = "hello ";
      var result = stringValue.concat("world", "!");
      alert(result);           // "hello world!"
      
      // 拼接字符串
      // 通用方式:
      var name = 'wusir', age = 28;
      var str = name + '今年是' + age + '岁了,快要结婚了,娶了个黑姑娘';
      // es6的模板字符串,使用``(Tab上面的那个键)
      var str2 = `${name}今年是${age}岁了,快要结婚了,娶了个黑姑娘`;
      
      
      • slice(),substr(),substring():基于子字符串创建新字符串的方法
      var stringValue = "hello world";
      // 正值情况下
      stringValue.slice(3);      // "lo world"
      stringValue.substring(3);      // "lo world"
      stringValue.substr(3));        // "lo world"
      
      stringValue.slice(3, 7);       // "lo w"
      stringValue.substring(3,7);    // "lo w"
      stringValue.substr(3, 7);      // "lo worl
      // 负值情况下
      stringValue.slice(-3);         // "rld" 
      stringValue.substring(-3);     // "hello world"
      stringValue.substr(-3);        // "rld"
      stringValue.slice(3, -4);      // "lo w" 
      stringValue.substring(3, -4);  // "hel"
      stringValue.substr(3, -4);     // ""(空字符串)
      
      
    5. 字符串位置方法

      • indexOf():从字符串的开头向后搜索子字符串
      • lastIndexOf():从字符串的末尾向前搜索子字符串
      var stringValue = "hello world";
      alert(stringValue.indexOf("o"));            // 4
      alert(stringValue.lastIndexOf("o"));        // 7
      alert(stringValue.indexOf("o", 6));         // 7
      alert(stringValue.lastIndexOf("o", 6));     // 4
      
      
    6. trim():删除字符串的前后空格

      var stringValue = "   hello world   ";
      stringValue.trim();       // "hello world"
      
      
    7. 字符串大小写转换方法

      • toUpperCase():小写转换成大写
      • toLowerCase():大写转换成小写
      var stringValue = "hello world";
      stringValue.toUpperCase();       // "HELLO WORLD"
      stringValue.toLowerCase();       // "hello world"
      

    11.3.3.4 日期对象:Date

    1. 日期对象的创建方式

      var myDate = new Date();
      
      
    2. 基本方法

      • getDate():返回指定日期对象的月份中的第几天
      • Date():返回当天的日期和时间
      • getMonth():返回指定日期对象的月份
      • getFullYear():返回指定日期对象的年份
      • getDay():返回指定日期对象的星期中的第几天
      • getHours():返回指定日期对象的小时
      • getMinutes():返回指定日期对象的分钟
      • getSeconds():返回指定日期对象的秒数
    3. 日期格式化方法

      • toLocaleString():以特定于实现的格式显示年月日,时分秒;
      • toDateString():以特定于实现的格式显示星期几、月、日和年
      • toTimeString():以特定于实现的格式显示时、分、秒和时区;
      • toUTCString():以特定于实现的格式完整的 UTC 日期
      var myDate = new Date();
      myDate.toLocaleString();    	// "2019/6/4 上午9:33:58"
      myDate.toDateString();          // "Mon Apr 15 2019"
      myDate.toTimeString();          // "10:11:53 GMT+0800 (中国标准时间)"
      myDate.toUTCString();		   // "Mon, 15 Apr 2019 02:11:53 GMT"
      
      
    4. 将今天的星期数显示在网页上,即写入body中,使用document.write

      var weeks = ['星期天','星期一','星期二','星期三','星期四','星期五','星期六'];
      console.log(weeks[date.getDay()]);
      var day = weeks[date.getDay()];
      document.write(`<a href="#">${day}</a>`);
      
      
      
    5. 数字时钟

      • 示例:返回了用数字时钟格式的时间
      var time = new Date();
      var hour = time.getHours();
      var minute = time.getMinutes();
      var second = time.getSeconds();
      var temp = "" + ((hour > 12) ? hour - 12 : hour);
      if (hour == 0)
          temp = "12";
      temp += ((minute < 10) ? ":0" : ":") + minute;
      temp += ((second < 10) ? ":0" : ":") + second;
      temp += (hour >= 12) ? " P.M." : " A.M.";
      alert(temp);
      
      
      • 升级版:在网页上显示数字时钟的动态效果
      <body>
      <h2 id="time"></h2>
      <script>
          var timeObj = document.getElementById('time');
          console.log(time);
          function getNowTime() {
              var time = new Date();
              var hour = time.getHours();
              var minute = time.getMinutes();
              var second = time.getSeconds();
              var temp = "" + ((hour > 12) ? hour - 12 : hour);
              if (hour == 0) {
                  temp = "12";
              }
              temp += ((minute < 10) ? ":0" : ":") + minute;
              temp += ((second < 10) ? ":0" : ":") + second;
              temp += (hour >= 12) ? " P.M." : " A.M.";
              timeObj.innerText = temp;
          }
          setInterval(getNowTime, 20)
      </script>
      </body>
      

    11.3.3.5 数学对象:Math

    1. min()和max()方法

      • Math.min():求最小值
      • Math.max():求最大值
      var max = Math.max(3, 54, 32, 16);
      alert(max);    // 54
      var min = Math.min(3, 54, 32, 16);
      alert(min);    // 3
      
      // 特殊:使用apply,找到数组中最大或最小值
      var values = [1,2,36,23,43,3,41];
      var max = Math.max.apply(null, values);
      
    2. 舍入方法

      • Math.ceil():天花板函数,只入不舍,相当于取整再加1
        • 执行向上舍入,即它总是将数值向上舍入为最接近的整数
      • Math.floor():地板函数,只舍不入,相当于取整
        • 执行向下舍入,即它总是将数值向下舍入为最接近的整数
      • Math.round():四舍五入,和数学中的取舍方式一致
        • 执行标准舍入,即它总是将数值四舍五入为最接近的整数
      var num = 25.7;
      var num2 = 25.2;
      Math.ceil(num);     // 26
      Math.floor(num);    // 25
      Math.round(num);    // 26
      Math.round(num2);   // 25
      
      
    3. random()方法

      • 用来取随机数
      • Math.random():方法返回大于等于0小于1的一个随机数
      // 例1:获取min到max的范围的整数
      function random(lower, upper) {
          return Math.floor(Math.random() * (upper - lower)) + lower;
      }
      
      // 例2: 获取随机颜色
      /* 产生一个随机的rgb颜色
      @return {String}  返回颜色rgb值字符串内容,如:rgb(201, 57, 96) */
      function randomColor() {
      	// 随机生成rgb值,每个颜色值在0-255之间
          var r = random(0, 256),
              g = random(0, 256),
              b = random(0, 256);
      	// 连接字符串的结果
          var result = "rgb("+ r +","+ g +","+ b +")";
          // 返回结果
          return result;
      }
      
      // 例3: 获取随机验证码
      function createCode(){
          //首先默认code为空字符串
          var code = '';
          //设置长度,这里看需求,我这里设置了4
          var codeLength = 4;
          //设置随机字符
          var random = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R', 'S','T','U','V','W','X','Y','Z'];
          //循环codeLength 我设置的4就是循环4次
          for(var i = 0; i < codeLength; i++){
              //设置随机数范围,这设置为0 ~ 36
              var index = Math.floor(Math.random()*36);
              //字符串拼接 将每次随机的字符 进行拼接
              code += random[index]; 
          }
          //将拼接好的字符串赋值给展示的Value
          return code
      }
      

    11.3.3.6 字符串和数值之间的转换

    1. 字符串转数值

      • parseInt():字符串转整数
      • perseFloat():字符串转浮点型
      • Number():字符串转数值
      var str = '123.0000111';			
      console.log(parseInt(str));			 // 123
      console.log(typeof parseInt(str));	  // number
      console.log(parseFloat(str));		 // 123.0000111
      console.log(typeof parseFloat(str));  // number
      console.log(Number(str));			 // 123.0000111
      
    2. 数值转字符串

      • toString():数值转字符串
      • 数字+空的字符串:数值转字符串
      var num  = 1233.006;
      // 强制类型转换
      console.log(String(num));
      console.log(num.toString());
      // 隐式转换
      console.log(''.concat(num));
      // toFixed()方法会按照指定的小数位返回数值的字符串 四舍五入
      console.log(num.toFixed(2));
      

    11.3.4 BOM

    • Brower Object Model:浏览器对象模型

    11.3.4.1 window对象

    1. 系统对话框方法

      • 警告框:window.alert();
      • 确认框:window.confirm();
      • 弹出框:window.prompt();
      window.alert('mjj');
      var a = window.confirm('你确定要删除?');
      console.log(a); 
      var weather = window.prompt('今天天气如何??');
      console.log(weather);
      
    2. 定时方法

      • setTimeout():一次性任务
        • 在5秒之后,执行相应的操作,可以做异步操作
      // 在5秒之后 执行相应的操作,可以做异步行为
      window.setTimeout(function(){
          console.log('111');
      },5000);
      console.log('2222');
      
      // 清除任务
      var timer = setTimeout(callback,2000);
      clearTimeout(timer);
      
      • setInterval():周期性循环
        • 可以使用clearInterval()来清除当前的定时任务,在开启定时器之前,要先清除掉定时器
      // 周期性定时器
      var num = 0;
      var timer = null;
      // 开启定时器
      timer = window.setInterval(function(){
          num++;
          if(num === 10){
              // 清除定时器
              clearInterval(timer);
          }
          console.log(num);
      },1000);
      
      • 总结:
        • setTimeout(callback,毫秒):一次性任务,延迟操作,异步
          setInterval(callback,毫秒):周期性循环任务,用于动画、css、transtion、tranform
    3. location对象

      • reload():重新加载,相当于刷新了整个页面,可用来做测试
      console.log(window.location);
      setInterval(function(){
          location.reload();
      },2000)
      
      • 局部刷新,使用ajax技术
        • ajax技术:在不重载页面的情况,对网页进行操作
    4. 示例:切换图片

      <div id="box">
          <img src="images/1.jpg" alt="" id="imgBox">
      </div>
      <button id="prev">上一张</button>
      <button id="next">下一张</button>
      <script type="text/javascript">
          var imgBox = document.getElementById('imgBox');
          var next = document.getElementById('next');
          var prev = document.getElementById('prev');
          var num = 1;
          next.onclick = function (){
              nextImg();
          };
          prev.onclick = function () {
              prevImg()
          };
          function nextImg(){
              num++;
              if(num === 5){
                  num = 1;
              }
              imgBox.src = `images/${num}.jpg`;
          }
          function prevImg(){
              num--;
              if(num === 0){
                  num = 4;
              }
              imgBox.src = `images/${num}.jpg`;
          }
          // 还可以使用定时器来循环切换,即setInterval(nextImg,1000);
      </script>
      

    11.3.5 DOM

    • Document Object Model:文档对象模型

    11.3.5.1 节点

    1. 节点的分类

      • 元素节点:各种标签
      • 文本节点:标签中的文本内容
      • 属性节点:标签中的属性
    2. 获取元素节点的方式

      • getElementById():通过id获取单个节点对象
      • getElementsByTagName():通过标签名获取节点对象
      • getElementsByClassName():通过类名获取节点对象
      // 1.通过id获取单个节点对象
      var box = document.getElementById('box');
      console.log(box);
      console.dir(box);
      console.log(box.children);
      // 2.通过标签名来获取节点对象 
      var box2 = document.getElementsByTagName('div');
      console.log(box2);
      var lis = document.getElementsByTagName('li');
      for(var i = 0; i < lis.length; i++){
      	lis[i].onclick = function(){
      		// 排他思想
          	for(var j = 0; j < lis.length; j++){
          		lis[j].className = '';
          	}
          	// this指向了绑定onclick的那个对象
          	this.className = 'active';
      	}
      }
      // 3.通过类名获取
      var lis2 = document.getElementsByClassName('active'); */
      console.log(lis2);
      
    3. 节点的创建、添加和删除

      • 创建节点:createElement()
        • 属性:
          • innerText:只能设置文本
          • innerHTML:既可以设置文本又可以设置标签 要是引用${},要用反引号
          • 针对与表单控件,使用value
            • inputText.value = '123';
      • 添加节点:
        • appendChild(newNode):在后面追加newNode
        • insertBefore(newNode,node):在node前插入newNode
      • 删除节点:removeChild()/ remove()
      var ul = document.getElementById('box');
      // 创建节点
      var li1 = document.createElement('li');
      var li2 = document.createElement('li');
      // innerText 只设置文本
      li1.innerText  = '你好';
      li1.innerHTML = '<a href="#">123</a>';
      li1.setAttribute('class','active');
      console.log(li1.children);
      
      li1.children[0].style.color = 'red';
      li1.children[0].style.fontSize = '20px';
      // 插入节点
      ul.appendChild(li1);
      li2.innerHTML = '第一个';
      ul.insertBefore(li2,li1);
      // 删除节点
      ul.removeChild(li2);
      
    4. 示例:遍历数据操作页面

      <style>
          ul li p.name{
              color: red;
          }
      </style>
      
      <body>
          <ul id="box"></ul>
          <script type="text/javascript">
              var box = document.getElementById('box');
              //从前端获取后端的数据
              var data = [
                  {id:1,name:'小米8',subName:'你真好',price:98},
                  {id:2,name:'小米6',subName:'你真好2',price:948},
                  {id:3,name:'小米4',subName:'你真好3',price:100},
                  {id:4,name:'小米2',subName:'你真好4',price:928},
                  {id:5,name:'小米10',subName:'你真好5',price:918}
              ];
              for(var i = 0; i < data.length; i++){
                  var li = document.createElement('li');
                  li.innerHTML = `<p class="name">${data[i].name}</p>
      <p class="subName">${data[i].subName}</p>
      <span class="price">${data[i].price}元</span>`;
                  box.appendChild(li);
              }
          </script>
      </body>
      

    11.3.5.2 属性操作

    1. 对样式操作

      • 修改样式:box.style.color等
      <style type="text/css">
      	#box{
      		 200px;
      		height: 200px;
      		background-color: red;
      	}
      </style>
      <div id="box">mjj</div>
      
      // 获取事件源对象
      var box = document.getElementById('box');
      // 绑定事件
      box.onmouseover = function (){
          // 让标签的背景色变绿
          box.style.backgroundColor = 'green';
          box.style.fontSize = '30px';
      }
      // 绑定事件
      box.onmouseout = function (){
          // 让标签的背景色变红
          box.style.backgroundColor = 'red';
          box.style.fontSize = '16px';
      } 
      
      // 单击更换背景色
      var isRed = true;
      box.onclick = function(){
          if(isRed){
              this.style.backgroundColor = 'green';
              isRed = false;
          }else{
              this.style.backgroundColor = 'red';
              isRed = true;
          }
      }
      
    2. 对属性操作

      • 获取标签上的属性:getAttribute
      • 修改标签上的属性:setAttribute
        • 如果是自定义的属性,要在文档上能看到,通过setAttribute设置属性
      <style type="text/css">
          .a{
              color: red;
              font-size: 30px;
          }
          p.active{
              color: blue;
          }
      </style>
      <p title="我的班级" id="p1" class="a">21</p>
      
      // 如果是自定义的属性,要在文档上能看到,通过setAttribute设置属性
      var p1 = document.getElementById('p1');
      console.log(p1.getAttribute('title'));
      p1.setAttribute('class','abc');
      console.log(p1.className);
      console.log(p1.title);
      console.dir(p1);
      /* p1.onclick = function(){
          this.className = this.className +' active';
      } */
      // // 单击更换颜色
      var isRed = true;
      p1.onclick = function(){
          if(isRed){
              this.className = this.className +' active';
              isRed = false;
          }else{
              this.className = 'a';
              isRed = true;
          }
      }
      
    3. 对类操作

      • 修改类:
        • box.className 类名可以找到这个类对应的value
        • box.title
      • 清除类:removeClass()

    11.3.6 js常用事件

    找到元素节点,然后给元素添加事件

    • onclick:鼠标单击事件
    • onmouseover:鼠标经过事件
    • onmouseout:鼠标移开事件
    • onchange:文本框内容改变事件
    • onselect:文本框内容被选中事件
    • onfocus:光标聚焦事件
    • onblur:光标失焦事件
    • onload:网页加载事件
  • 相关阅读:
    vuejs 踩坑及经验总结
    Factory Method
    【Java】macOS下编译JDK8
    康威定律(Conway's law)
    first-child和first-of-type
    JavaScript 核心学习——继承
    All Tips
    21分钟教会你分析MaxCompute账单
    CTO职场解惑指南系列(一)
    威胁预警|首现新型RDPMiner挖矿蠕虫 受害主机易被添加恶意账户
  • 原文地址:https://www.cnblogs.com/hanfe1/p/12063597.html
Copyright © 2011-2022 走看看