Javascript-基础

规范

CSS-规范

http://alloyteam.github.io/CodeGuide/#project-naming

  • 属性书写顺序

    • class

    • id

    • name

    • data-*

    • src, for, type, href, value , max-length, max, min, pattern

    • placeholder, title, alt

    • aria-*, role

    • required, readonly, disabled

      class 是为高可复用组件设计的,所以应处在第一位;

      id 更加具体且应该尽量少使用,所以将它放在第二位。

  • 命名

    • 类名使用小写字母,以中划线分隔

      1
      2
      3
      4
      /* class */
      .element-content {
      ...
      }
    • id 采用驼峰式命名

      1
      2
      3
      4
      /* id */
      #myDialog {
      ...
      }
    • scss 中的变量、函数、混合、placeholder采用驼峰式命名

  • 属性声明顺序

    • 相关的属性声明按右边的顺序做分组处理,组之间需要有一个空行。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      .declaration-order {
      display: block;
      float: right;

      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      z-index: 100;

      border: 1px solid #e5e5e5;
      border-radius: 3px;
      width: 100px;
      height: 100px;

      font: normal 13px "Helvetica Neue", sans-serif;
      line-height: 1.5;
      text-align: center;

      color: #333;
      background-color: #f5f5f5;

      opacity: 1;
      }
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      /* 下面是推荐的属性的顺序 */
      [ [ "display", "visibility", "float", "clear", "overflow", "overflow-x", "overflow-y", "clip", "zoom" ],
      [ "table-layout", "empty-cells", "caption-side", "border-spacing", "border-collapse", "list-style", "list-style-position", "list-style-type", "list-style-image" ],
      [ "-webkit-box-orient", "-webkit-box-direction", "-webkit-box-decoration-break", "-webkit-box-pack", "-webkit-box-align", "-webkit-box-flex" ],
      [ "position", "top", "right", "bottom", "left", "z-index" ],
      [ "margin", "margin-top", "margin-right", "margin-bottom", "margin-left", "-webkit-box-sizing", "-moz-box-sizing", "box-sizing", "border", "border-width", "border-style", "border-color", "border-top", "border-top-width", "border-top-style", "border-top-color", "border-right", "border-right-width", "border-right-style", "border-right-color", "border-bottom", "border-bottom-width", "border-bottom-style", "border-bottom-color", "border-left", "border-left-width", "border-left-style", "border-left-color", "-webkit-border-radius", "-moz-border-radius", "border-radius", "-webkit-border-top-left-radius", "-moz-border-radius-topleft", "border-top-left-radius", "-webkit-border-top-right-radius", "-moz-border-radius-topright", "border-top-right-radius", "-webkit-border-bottom-right-radius", "-moz-border-radius-bottomright", "border-bottom-right-radius", "-webkit-border-bottom-left-radius", "-moz-border-radius-bottomleft", "border-bottom-left-radius", "-webkit-border-image", "-moz-border-image", "-o-border-image", "border-image", "-webkit-border-image-source", "-moz-border-image-source", "-o-border-image-source", "border-image-source", "-webkit-border-image-slice", "-moz-border-image-slice", "-o-border-image-slice", "border-image-slice", "-webkit-border-image-width", "-moz-border-image-width", "-o-border-image-width", "border-image-width", "-webkit-border-image-outset", "-moz-border-image-outset", "-o-border-image-outset", "border-image-outset", "-webkit-border-image-repeat", "-moz-border-image-repeat", "-o-border-image-repeat", "border-image-repeat", "padding", "padding-top", "padding-right", "padding-bottom", "padding-left", "width", "min-width", "max-width", "height", "min-height", "max-height" ],
      [ "font", "font-family", "font-size", "font-weight", "font-style", "font-variant", "font-size-adjust", "font-stretch", "font-effect", "font-emphasize", "font-emphasize-position", "font-emphasize-style", "font-smooth", "line-height", "text-align", "-webkit-text-align-last", "-moz-text-align-last", "-ms-text-align-last", "text-align-last", "vertical-align", "white-space", "text-decoration", "text-emphasis", "text-emphasis-color", "text-emphasis-style", "text-emphasis-position", "text-indent", "-ms-text-justify", "text-justify", "letter-spacing", "word-spacing", "-ms-writing-mode", "text-outline", "text-transform", "text-wrap", "-ms-text-overflow", "text-overflow", "text-overflow-ellipsis", "text-overflow-mode", "-ms-word-wrap", "word-wrap", "-ms-word-break", "word-break" ],
      [ "color", "background", "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader", "background-color", "background-image", "background-repeat", "background-attachment", "background-position", "-ms-background-position-x", "background-position-x", "-ms-background-position-y", "background-position-y", "-webkit-background-clip", "-moz-background-clip", "background-clip", "background-origin", "-webkit-background-size", "-moz-background-size", "-o-background-size", "background-size" ],
      [ "outline", "outline-width", "outline-style", "outline-color", "outline-offset", "opacity", "filter:progid:DXImageTransform.Microsoft.Alpha(Opacity", "-ms-filter:\\'progid:DXImageTransform.Microsoft.Alpha", "-ms-interpolation-mode", "-webkit-box-shadow", "-moz-box-shadow", "box-shadow", "filter:progid:DXImageTransform.Microsoft.gradient", "-ms-filter:\\'progid:DXImageTransform.Microsoft.gradient", "text-shadow" ],
      [ "-webkit-transition", "-moz-transition", "-ms-transition", "-o-transition", "transition", "-webkit-transition-delay", "-moz-transition-delay", "-ms-transition-delay", "-o-transition-delay", "transition-delay", "-webkit-transition-timing-function", "-moz-transition-timing-function", "-ms-transition-timing-function", "-o-transition-timing-function", "transition-timing-function", "-webkit-transition-duration", "-moz-transition-duration", "-ms-transition-duration", "-o-transition-duration", "transition-duration", "-webkit-transition-property", "-moz-transition-property", "-ms-transition-property", "-o-transition-property", "transition-property", "-webkit-transform", "-moz-transform", "-ms-transform", "-o-transform", "transform", "-webkit-transform-origin", "-moz-transform-origin", "-ms-transform-origin", "-o-transform-origin", "transform-origin", "-webkit-animation", "-moz-animation", "-ms-animation", "-o-animation", "animation", "-webkit-animation-name", "-moz-animation-name", "-ms-animation-name", "-o-animation-name", "animation-name", "-webkit-animation-duration", "-moz-animation-duration", "-ms-animation-duration", "-o-animation-duration", "animation-duration", "-webkit-animation-play-state", "-moz-animation-play-state", "-ms-animation-play-state", "-o-animation-play-state", "animation-play-state", "-webkit-animation-timing-function", "-moz-animation-timing-function", "-ms-animation-timing-function", "-o-animation-timing-function", "animation-timing-function", "-webkit-animation-delay", "-moz-animation-delay", "-ms-animation-delay", "-o-animation-delay", "animation-delay", "-webkit-animation-iteration-count", "-moz-animation-iteration-count", "-ms-animation-iteration-count", "-o-animation-iteration-count", "animation-iteration-count", "-webkit-animation-direction", "-moz-animation-direction", "-ms-animation-direction", "-o-animation-direction", "animation-direction" ],
      [ "content", "quotes", "counter-reset", "counter-increment", "resize", "cursor", "-webkit-user-select", "-moz-user-select", "-ms-user-select", "user-select", "nav-index", "nav-up", "nav-right", "nav-down", "nav-left", "-moz-tab-size", "-o-tab-size", "tab-size", "-webkit-hyphens", "-moz-hyphens", "hyphens", "pointer-events" ]
      ]
    • 属性简写

      属性简写需要你非常清楚属性值的正确顺序,而且在大多数情况下并不需要设置属性简写中包含的所有值,所以建议尽量分开声明会更加清晰;

      1
      marginpadding 相反,需要使用简写;
      • 常见简写属性
        • font
        • background
        • transition
        • animation
Javascript-规范
  • 引号

    最外层统一使用单引号。

    1
    2
    3
    // good
    var y = 'foo',
    z = '<div id="test"></div>';
  • 变量命名

    • 标准变量采用驼峰式命名(除了对象的属性外,主要是考虑到cgi 返回的数据)
    • ID 在变量名中全大写
    • URL 在变量名中全大写
    • Android 在变量名中大写第一个字母
    • iOS 在变量名中小写第一个,大写后两个字母
    • 常量全大写,用下划线连接
    • 构造函数,大写第一个字母
    • jquery 对象必须以$ 开头命名
  • 变量声明

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    // 一个函数作用域中所有的变量声明尽量提到函数首部,用一个var声明,不允许出现两个连续的var声明。
    unction doSomethingWithItems(items) {
    // use one var
    var value = 10,
    result = value + 10,
    i,
    len;

    for (i = 0, len = items.length; i < len; i++) {
    result += 10;
    }
    }
  • null

    • 适宜场景

      • 初始化一个将来可能被赋值为对象的变量
      • 与已经初始化的变量做比较
      • 作为一个参数为对象的函数的调用传参
      • 作为一个返回对象的函数的返回值
    • 不适用场景:

      • 不要用null 来判断函数调用时有无传参

      • 不要与未初始化的变量做比较

chrome调试

  • 调试

    1
    debugger

Javascrip-面向对象

  • 对象类型的基本使用

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // 对象类型是一种 存储键值对 的更复杂的数据类型

    // 1. 字面量创建对象(字面量创建)
    const obj = {
    name: "coder",
    age: 18,
    sayHello: function () {
    console.log("say..........");
    }
    };
    console.log(obj)
  • 创建对象和使用对象

    1
    2
    3
    4
    // 2. new Object()
    var obj2 = new Object();
    obj2.name = "李四";
    console.log(obj2);
  • 对象的方括号

    1
    2
    3
    4
    var info = {
    "good frend": "王五"
    }
    console.log(info['good frend'])
  • 对象的遍历

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    // 普通循环(存在索引)
    for (var item = 0; item < Object.keys(obj).length; item++) {
    console.log(Object.keys(obj)[item])
    }

    // for...in...(无索引)
    for (var key in obj) {
    console.log(obj[key])
    }

栈内存和堆内存

  • 原始类型占据空间是在栈内存中分配的

  • 对象类型占据空间是在堆内存中分配的

  • 对象的比较

    1
    2
    3
    4
    var obj1 = {};
    var obj2 = {};
    // false => 指向不同的地址
    console.log(obj1 === obj2)
  • 对象的引用赋值

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    var obj1 = {
    frend: {
    name: "aa"
    }
    };
    var obj2 = {};
    obj2.info = obj1.frend;
    obj2.info.name = "bb"
    // bb
    console.log(obj1.frend.name)
  • 值传递和引用传递的区别

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    function foo() {
    a = 200;
    }
    var num = 100;
    foo(num)
    // 值传递 100
    console.log(num);


    function foo(a) {
    a = {
    name: "name"
    }
    }
    var obj = {
    name: "obj"
    }
    foo(obj)
    // {name: 'obj'}
    console.log(obj)
    内存分析
  • 函数中this 指向

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    // 情况一: 如果普通的函数默认调用,那么 this 就指向 window
    function foo(name, age) {
    console.log(arguments);
    console.log(this);
    }
    foo("coder", 18)

    // 情况二: 如果函数它是被某一个对象来引用并且调用它,那么 this 就指向这个对象(调用的这个对象)
    var obj = {
    name: "username",
    running: function () {
    console.log(this)
    console.log(obj)
    // true
    console.log(obj === this)
    }
    };
    obj.running();

    // 默认调用 this => window
    var fn = obj.running;
    fn();
    this 指向
  • 实际应用

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    var obj = {
    name: "coder",
    running: function () {
    console.log(this.name + "在running~~")
    },
    eating: function () {
    console.log(this.name + "在eating~~")
    }
    };
    obj.running();
    obj.eating();
  • 工厂函数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    function createStudent(name) {
    var obj = {
    };

    obj.name = name;
    obj.running = function () {
    console.log(this.name + "在running~~")
    };
    obj.eatingg = function () {
    console.log(this.name + "在eating~~")
    }
    return obj;
    }
    var stu1 = createStudent("a");
    var stu2 = createStudent("b");
    var stu3 = createStudent("c");

    // 推荐用法(构造函数)
    function Coder(name) {
    this.name = name;
    }
    var info = new coder("a");
    console.log(info)

常见的内置类

  • 包装类型

    1
    2
    3
    4
    5
    // 原始类型的包装类
    var message = "Hello World";
    // new String(message)
    console.log(message.length)

  • 常见的包装类型:String,Number,Boolean,Symbol,BigInt 类型

  • 包装类型的使用过程

    1. 根据原始值,创建一个原始类型对应的包装类型对象
    2. 调用对应的属性或者方法,返回一个新的值
    3. 创建的包装类对象被销毁
  • Number 类的补充

    • Number 实例方法补充
      • toString(base) 将数字转换为字符串,并且按照base 进制转换,base 默认10
      • toFixed(digits) 格式化一个数字,保留digits 位小数
    • Number 类方法补充
      • Number.parseInt(string[,radix]) 将字符串解析成整数,也有对应的全局方法parseInt
      • Number.parseFloat(string) 将字符串解析为浮点数,也有对应的全局方法parseFloat
  • Math

    • Math 是一个内置对象(不是一个构造函数) 拥有一些数字常熟属性和数学函数的方法

    • 补充

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      console.log(typeof Math); // object

      // Math 不是构造函数
      new Math(); // index.html:13 Uncaught TypeError: Math is not a constructor

      Math.floor(); // 向下舍入取整
      Math.ceil(); // 向上舍入取整
      Math.round(); // 四舍五入取整
      Math.random(); // 生成 0 ~ 1的随机数 => [0,1)
      Math.pow(x, y); // 返回 x 的 y 次幂
  • String 类补充

    • 常见属性: length

    • 访问字符串章某个位置的字符

      1
      2
      3
      var message = "Hello World";
      console.log(message[4]); // o
      console.log(message.charAt(4)); // o
    • 字符串的遍历

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      var message = "Hello World";
      // 普通遍历
      for (var i = 0; i < message.length; i++) {
      console.log(message[i]);
      }

      // for...of...
      for (var i of message) {
      console.log(i)
      }

    • 字符串修改

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      // 字符串是不可变的
      var message = "Hello World";
      message[2] = "A";
      // 无意义 => Hello World
      console.log(message);


      // 修改 字符编程大小写
      var message1 = message.toUpperCase();
      // HELLO WORLD
      console.log(message1)

      var message2 = message.toLowerCase();
      // hello world
      console.log(message2)

    • 查找字符串

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      var message = "my name is javascript";
      var name = "javascript";
      /*
      indexOf:
      情况一: 搜索到,搜索字符所在索引位置
      情况二: 没有搜索到,返回 -1
      */
      var index = message.indexOf(name);
      console.log(index);

      // includes() 判断包含关系
      // startsWith() 是否以 xxx 开头
      // endsWith() 是否以 xxx 结尾
      // replace(searchValue,replaceValue) 替换字符串
    • 获取子字符串

      方法 选则方式 负值参数
      slice(start,end) start end,不包含end 允许
      substring(start,end) start end,不包含end 负值代表0
      substr*start,length() start 开始获取长为length 的字符串 允许start 为负数
    • 字符串的拼接

      1
      2
      3
      // 1. +

      // 2. concat
    • 删除首位的空格

      1
      // trim
    • 字符串的切割

      1
      2
      3
      4
      // split
      var message = "abc-def-ss-aa";
      //  ['abc', 'def', 'ss', 'aa']
      console.log(message.split("-"))

数组(Array)

  • 创建数组

    1
    2
    3
    4
    5
    6
    // 方式一
    var names = ["coder", "huanhuan"];

    // 方式二
    var arr = new Array("a","b");

  • 数组的基本操作

    • 访问

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      // 中括号访问 不支持负数获取
      var names = ["coder", "huanhuan"];
      console.log(names[0]);

      // at(i)
      // 如果 i >= 0 则与 arr[i] 完全相同
      // 对于 i 为负数,它则从数组的尾部向前数
      var names = ["coder", "huanhuan"];
      // huanhuan 支持负数
      console.log(names.at(-1))
    • 删除数组中的元素

      1
      2
      3
      4
      5
      // 了解内容
      var names = ["coder", "huanhuan"];
      delete names[1];
      // ['coder', empty]
      console.log(names);
      1
      2
      3
      4
      5
      6
      7
      8
      9
      // 掌握内容
      var names = ["coder", "huanhuan"];

      // 在数组的尾部添加和删除元素
      // push(尾部追加) 方法
      names.push("yingying")
      // (3) ['coder', 'huanhuan', 'yingying']
      console.log(names);

      1
      2
      3
      4
      // 删除尾部元素 pop(默认删除数组元素中最后一个元素)
      names.pop()
      // ['coder']
      console.log(names);
      1
      2
      3
      4
      5
      6
      // 在数组的头部添加元素
      // unshift
      var names = ["coder", "huanhuan"];
      names.unshift("a", "b");
      // (4) ['a', 'b', 'coder', 'huanhuan']
      console.log(names);
      1
      2
      3
      4
      5
      // 删除头部的一个元素
      var names = ["coder", "huanhuan"];
      names.shift();
      // ['huanhuan']
      console.log(names);
      效率问题
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      // 在指定位置添加或删除元素、替换元素 arr.splice
      var names = ["coder", "huanhuan", "aa", "bb"];

      // 添加: deleteCount=0
      names.splice(1, 0, "add1", "add2")
      // (6) ['coder', 'add1', 'add2', 'huanhuan', 'aa', 'bb']
      console.log(names)
      // 删除

      /*
      参数一:
      start 从什么位置开始操作元素
      deleteCount 删除元素的个数
      */
      names.splice(1, 1)
      // Array(3)
      console.log(names)
      // 替换: 先删除后添加
      names.splice(1, 2,"replace1","replace2")
  • 数组的遍历

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    // 普通遍历(存在索引)
    var names = ["coder", "huanhuan", "aa", "bb"];
    for (var item = 0; item < names.length; item++) {
    console.log(names[item])
    }


    // for in(存在索引)
    var names = ["coder", "huanhuan", "aa", "bb"];
    for (var index in names) {
    // 0 coder...
    console.log(index, names[index])
    }

    // for of(无索引)
    for (var item of names) {
    // coder...
    console.log(names[item])
    }

  • slice,concat,join

    1
    2
    3
    4
    5
    6
    // slice
    var names = ["coder", "huanhuan", "aa", "bb", "dd", "ww", "ff"];
    // slice 不会修改原数组,splice会修改原数组
    var new_arr = names.slice(2, 4);
    // (2,4]:  ['aa', 'bb']
    console.log(new_arr);
    1
    2
    3
    4
    5
    6
    7
    // concat
    var names = ["coder", "huanhuan", "ww", "ff"];
    var name1 = ["aa", "bb", "dd"];
    // 需要接受
    var new_arr = names.concat(name1);
    // (7) ['coder', 'huanhuan', 'ww', 'ff', 'aa', 'bb', 'dd']
    console.log(new_arr);
    1
    2
    // join: coder-huanhuan-ww-ff-aa-bb-dd
    console.log(new_arr.join("-"));
  • 数组查找元素

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    // 1. 可以找到,返回对应的索引 没有找到,返回 -1(原始类型数据可用 indexOf)
    names.indexOf("javascript")

    // 2. find 方法
    var info = [{ name: "ls" }, { name: "wu" }];
    var stu = info.find((item) => {
    // 获取到的是数组中的每一个对象
    console.log(item);
    //
    if (item.name === "ls") {
    return true;
    }
    })
    console.log(stu);

    var arr = ["ls", "wu"];
    arr.find((item) => {
    console.log(item);
    })

    1
    2
    3
    4
    5
    // 直接查找元素或者索引
    var arr = ["ls", "wu"];
    arr.findIndex((item, index, arr) => {
    console.log(item, index, arr);
    })
    1
    2
    3
    4
    // 判断数组是否包含某个元素
    var arr = ["ls", "wu"];
    // true
    console.log(arr.includes("ls"));
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // sort
    var arr = [100, 10, 89, 200, 3000];
    // 默认升序
    arr.sort()

    console.log(arr.sort((item1, item2) => {
    // 从大到小 (5) [3000, 200, 100, 89, 10]
    return item2 - item1;
    }));


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // 复杂类型的排序
    var students = [
    { id: 1001, name: "ls", age: 18 },
    { id: 1002, name: "wu", age: 68 },
    { id: 1003, name: "lk", age: 28 },
    { id: 1004, name: "sj", age: 8 }
    ];
    students.sort((item1, item2) => {
    return item1.age - item2.age
    })
    console.log(students);
    排序
  • forEach 函数

    1
    2
    3
    students.forEach(item => {
    console.log(item);
    })
  • filter 过滤

    1
    2
    3
    4
    5
    6
    var arr = [11, 20, 299, 70];
    var newNums = arr.filter(item => {
    return item % 2 == 0;
    })
    // 过滤结果需要接受
    console.log(newNums);
  • map 函数

    1
    2
    3
    4
    5
    6
    var arr = [11, 20, 299, 70];
    var mapArr = arr.map(item => {
    return item * item;
    })
    // 获取数组元素的平方
    console.log(mapArr);
  • reduce

    1
    2
    3
    4
    5
    6
    7
    // reduce: 累加 0 是初始值  0+11=11,11+20=31,...
    var arr = [11, 20, 299, 70];
    var reduceArr = arr.reduce((preValue, item) => {
    return preValue + item;
    }, 0)
    console.log(reduceArr);

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    // 练习 reduce:
    var products = [
    { name: "鼠标", price: 80, count: 3 },
    { name: "电脑", price: 3980, count: 1 },
    { name: "耳机", price: 9.9, count: 23 }
    ];
    var totalPrice = products.reduce((preValue, item) => {
    return preValue + item.price + item.count;
    }, 0)
    console.log(totalPrice);
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    // 过滤所有的偶数,映射所有的偶数平方和,并且计算它们的和
    // 过滤所有的偶数,映射所有的偶数平方和,并且计算它们的和
    var arr = [11, 20, 55, 100, 88, 32];

    var total = arr.filter(item => {
    return item % 2 == 0;
    }).map(item => {
    return item * item;
    }).reduce((prevalue, item) => {
    return prevalue + item;
    }, 0)
    console.log(total)

日期

  • 创建Date 对象

    1
    2
    3
    var date1 = new Date();
    // 获取当前时间: Thu Sep 01 2022 11:06:18 GMT+0800 (中国标准时间)
    console.log(date1);
  • 时间字符串

    1
    2
    3
    var date2 = new Date("2023-01-12");
    // Thu Jan 12 2023 08:00:00 GMT+0800 (中国标准时间)
    console.log(date2);
  • 传入具体时间

    1
    2
    3
    4
    5
    6
    7
    // 2022-09-01 11:30:26
    var date3 = new Date(2022, 09, 01, 11, 30, 26);
    // Sat Oct 01 2022 11:30:26 GMT+0800 (中国标准时间)
    console.log(date3);

    // 1s = 1000ms

  • 时间的两种标准方式

    • RFC 2822 标准(默认打印使用的标准)
    • ISO 8601 标准
  • 获取自己的格式化方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    var date = new Date();
    // 获取年份(4位数)
    var year = date.getFullYear();
    // 获取月份(从 0 到 11)
    var month = date.getMonth() + 1;
    // 获取当月的具体日期(从 1 到 31)
    var day = date.getDate();
    // 获取小时
    var hour = date.getHours();
    // 获取分钟
    var minutes = date.getMinutes();
    // 获取秒钟
    var seconds = date.getSeconds();
    // 获取毫秒
    var milliSeconds = date.getMilliseconds();

    // 2022 9 1 11 21 49 31
    console.log(year, month, day, hour, minutes, seconds, milliSeconds);
  • 获取Unix 时间戳

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    var date = new Date();
    // 1. 当前时间的时间戳
    var timestamp = Date.now();
    console.log(timestamp);

    // 2. getTime() | valueOf()
    var timestamp2 = date.getTime();
    console.log(timestamp2);

    // +date
    console.log(+date)


    Date.parse(date)

    1
    2
    3
    4
    5
    6
    7
    8
    // 计算这个操作所花费的时间
    var startTime = Date.now();
    for (var i = 0; i < 10000; i++) {
    console.log(i);
    }
    var endtime = Date.now();
    console.log("执行时间为: ", endtime - startTime);

DOM

  • Dom: 将页面所有的内容表示为可以修改的对象

  • Bom:由浏览器提供的用于处理文档之外的所有的内容的其他对象

  • Dom Tree

    Dom Tree
  • Dom 元素之间的关系

    • Dom 的继承关系图

      继承关系图
    • document 对象

      1
      2
      3
      4
      var htmlEl = document.documentElement;
      var bodyEl = document.body;
      var headEl = document.head;
      console.log(htmlEl, bodyEl, headEl);
    • 节点导航

      节点导航
    • table form 的导航关系

      • table.rows :tr 元素的集合

      • table.caption/tHead/tFoot 引用元素

      • table.tBodies:tbody 的元素集合

      • <thead>,<tffot>,<tbody>:元素提供了rows 属性

      • tr

        • tr.cells 在给定tr 中的td th 单元格的集合
        • tr.sectionRowIndex 给定的tr 在封闭的<thead>/<tbody>/<tfoot> 中的位置(索引)
        • tr.rowIndex 在整个表格中tr 的编号(包括表格的所有行)
      • table 案例

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
        40
        41
        42
        43
        44
        45
        46
        47
        48
        49
        50
        51
        52
        53
        54
        55
        56
        <!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>
        table {
        border-collapse: collapse;
        }

        td {
        border: 1px solid #000;
        padding: 18px 22px;
        }
        </style>
        </head>

        <body>
        <table>
        <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        </tr>
        <tr>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        </tr>
        <tr>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        </tr>
        </table>
        <script>
        // 获取 table
        var tableEl = document.body.firstElementChild;
        for (var i = 0; i < tableEl.rows.length; i++) {
        // 获取第一行
        var rowEl = tableEl.rows[i];
        // 获取第一行第一个
        var cellEl = rowEl.cells[i];
        // ceilEl.innerHTML 获取文本
        console.log(cellEl.innerHTML);
        // 设置样式
        cellEl.style.background = "red";
        cellEl.style.color = "white"
        }
        </script>
        </body>

        </html>
        Dom 元素获取
  • 获取Dom 元素

    1
    2
    3
    4
    // 根据类名称获取
    // document.getElementsByClassName("keyword")[i];
    var keyWorld = document.getElementsByClassName("keyword");
    console.log(keyWorld);
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11

    <body>
    <div class="box">
    <span id="keyword">name:coder</span>
    </div>
    <script>
    // 通过 id 获取
    var keyWord = document.getElementById("keyword");
    console.log(keyWord);
    </script>
    </body>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <body>
    <div class="box">
    <span id="keyword">name:coder</span>
    </div>
    <script>
    // querySelector
    var keyWord = document.querySelectorAll("#keyword");
    // querySelectorAll
    var box = document.querySelectorAll(".box");
    console.log(keyWord);
    console.log(box);
    </script>
    </body>
  • 节点的属性

    1
    2
    3
    4
    // innerHTML // 可以解析标签

    // textContent 不解析标签元素

  • Dom 节点的attributes,properties

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    // attributes 属性 所有的值都是字符串
    // 获取元素
    var boxEl = document.querySelector(".box");
    // 所有 attribute 都支持的操作
    // 1. 检查特性是否存在 false
    console.log(boxEl.hasAttribute("name"));
    // 2. 获取这个特性值
    console.log(boxEl.getAttribute("title"));
    // 3. 设置这个特性值
    boxEl.setAttribute("key", "value");
    // 4. 移除这个特性值
    boxEl.removeAttribute("height");
    console.log(boxEl);

    // properties

  • Javascript 动态修改样式

    1
    2
    3
    4
    5
    6
    // 添加一个类(不推荐)
    boxEl.className = "active";

    // 动态修改宽度
    boxEl.style.width = "100px";

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // classList
    // 获取元素
    var boxEl = document.querySelector(".box");
    // 添加一个类
    boxEl.classList.add("active");
    // 移除类
    boxEl.classList.remove("active");
    // 如果类不存在就添加类,存在就移除它
    boxEl.classList.toggle("aa");
    // 检查给定类
    boxEl.classList.contains("aa");
  • 元素的style

    1
    2
    3
    4
    5
    6
    7
    8
    // 多单词使用小驼峰命名
    boxEl.style.backgroundColor = "red";

    // 属性值设置为空字符串,使用默认值
    boxEl.style.display = "";

    // 设置多个样式
    boxEl.style.cssText = "font-size: 30px;color: red;";
  • style 的读取

    1
    2
    3
    var boxEl = document.querySelector(".box");
    // 16px
    console.log(getComputedStyle(boxEl).fontSize);
  • dataset

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <body>
    <!-- 设置自定义属性: data-height => height -->
    <div class="box" title="aa" data-height="12">
    获取元素
    </div>
    <script>
    var boxEl = document.querySelector(".box");
    // 获取 data-height 的值: 12
    console.log(boxEl.dataset.height);
    </script>
    </body>

  • Dom 节点的创建、插入、克隆、删除

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    // 1. 创建元素
    var boxEl = document.querySelector(".box");
    // 1. innerHTML => 替换了 box 内的内容(不推荐)
    boxEl.innerHTML = "<h2>H2</h2>"

    // 2. 创建一个 DOM 对象
    var h3 = document.createElement("h3");
    // 插入元素位置 boxEl 的子元素
    boxEl.appendChild(h3)

    // 在 boxEl 开头插入节点或字符串
    boxEl.prepend(...nodes or strings);
    // 在 boxEl 前面插入节点或字符串
    boxEl.before(...nodes or strings);
    // 在 boxEl 后面插入节点或字符串
    boxEl.after(...nodes or strings);
    // 将 boxEl 替换为给定的节点或字符串
    boxEl.replaceWith(...nodes or strings);
    1
    2
    3
    4
    5
    6
    7
    // 移除: boxEl.remove();

    var boxEl = document.querySelector(".box");
    // 克隆 true => 深度克隆
    var cloneNode = boxEl.cloneNode(true)
    // 插入节点
    boxEl.after(cloneNode);
    clone
  • Dom 元素window 的大小,滚动,坐标

    • clientWidth: contetnWidth + padding(不包含滚动条)

    • clientHeight: contentHeight + padding(不包含滚动条)

    • clientTop ,clientLeft

    • offsetWidth: 元素完整的宽度

    • offsetHeight 元素完整的高度

    • offsetleft 距离父元素的x

    • offsetTop: 距离父元素的y

    • scrollHeight 整个可滚动的区域高度

    • scrollTop 滚动部分的高度

      理解
  • Window 的大小、滚动

    • innerWidth、innerHeight 获取window 窗口的宽度和高度(包含滚动条)
    • outerWidth、outerHeight 获取window 窗口的整个宽度和高度(包括调式工具栏、工具栏)
    • documenrElement.clientHeight,documenrElement.clientWidth 获取HTML 的宽度和高度(不包含滚动条)
  • window 的滚动位置

    • scrollX: X轴滚动的位置别名pageXOffset
    • scrollY:y轴滚动的位置别名pageYOffset
  • 滚动方法

    • scrollBy(x,y) 将页面滚动至相对于当前位置的x,y 位置
    • 方法scrollTo(pageX,pageY) 将页面滚动至绝对坐标
  • 案例练习

    • 动态创建列表

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      <!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></style>
      </head>
      <ul class="list"></ul>
      <body>
      <script>
      var listEl = document.querySelector(".list");
      var isFlag = true;
      while (isFlag) {
      var message = prompt("请输入信息: ");
      // 没有输入内容
      if (!message) {
      isFlag = false;
      } else {
      // 创建 li
      var createLiEl = document.createElement("li");
      createLiEl.textContent = message;
      listEl.append(createLiEl);
      }
      }
      </script>
      </body>
      </html>

    • 倒计时

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      <!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>倒计时</title>
      <style>
      .count_down {
      color: red;
      }
      .count_down .time {
      display: inline-block;
      color: #fff;
      padding: 5px;
      border-radius: 3px;
      background-color: #f00;
      }
      </style>
      </head>
      <body>
      <div class="count_down">
      <span class="time hour">02</span>
      <span class="split">:</span>
      <span class="time minute">24</span>
      <span class="split">:</span>
      <span class="time second">10</span>
      </div>

      <script>
      setInterval(function () {
      function formatPadLeft(content, count, padStr) {
      count = count || 2;
      padStr = padStr || "0";
      content = String(content);
      return content.padStart(count, padStr);
      }

      var houtEl = document.querySelector(".hour");
      var minuteEl = document.querySelector(".minute");
      var secondEl = document.querySelector(".second");

      // 获取倒计时的小时 -> 分钟 -> 秒钟
      var nowDate = new Date();
      var endDate = new Date();
      // 设置倒计时将来的时间(24小时制)
      endDate.setHours(16);
      endDate.setMinutes(0);
      endDate.setSeconds(0);
      endDate.setMilliseconds(0);

      // 间隔: (endDate.getTime() - nowDate.getTime()) => ms(毫秒)/1000 => s(秒)
      var intervalTime = Math.floor(
      (endDate.getTime() - nowDate.getTime()) / 1000
      );
      console.log(intervalTime);

      var hour = Math.floor(intervalTime / 3600);
      var minute = Math.floor(intervalTime / 60) % 60;
      var second = intervalTime % 60;

      // 设置内容
      houtEl.textContent = formatPadLeft(hour);
      minuteEl.textContent = formatPadLeft(minute);
      secondEl.textContent = formatPadLeft(second);
      }, 1000);
      </script>
      </body>
      </html>

      倒计时
  • 常见的鼠标事件

    属性 描述
    click 当用户点击某个对象时调用的事件句柄
    contextmenu 在用户点击鼠标右键打开上下文菜单时触发
    dblclick 当用户双击某个对象时调用的事件句柄
    mousedown 鼠标按钮被按下
    mouseup 鼠标按键被松开
    mouseover 鼠标移动某元素之上(支持冒泡)
    mouseout 鼠标从某元素移开支持冒泡
    mouseenter 当鼠标指针移动到元素上时触发不支持冒泡
    mouseleave 当鼠标指针移出元素时触发(不支持冒泡)
    mousemove 鼠标被移动
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    var divEl = document.querySelector(".box");
    // 单击事件
    divEl.onclick = function () {
    console.log("divEl", divEl);
    };
    // 鼠标右键
    divEl.oncontextmenu = function (event) {
    // 关闭右键显示
    event.preventDefault();
    console.log("oncontextmenu");
    };
    // 鼠标按下
    divEl.onmousedown = function () {
    console.log("onmousedown");
    };
    • mouseover mouseenter 的区别

      • mouseenter mouseleave

        • 不支持冒泡
        • 进入子元素依然属于该元素内m没有任何反应
      • mouseover mouseout

        • 支持冒泡
        • 进入元素的子元素时
          1. 先调用父元素的mouseout
          2. 再调用子元素的mouseover
          3. 因为支持冒泡,所以会将mouseover 传递到父元素中
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        <!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 {
        background-color: orange;
        }
        </style>
        </head>
        <body>
        <div class="box">
        <button>删除</button>
        <button>新增</button>
        <button>搜索</button>
        </div>

        <script>
        var boxEl = document.querySelector(".box");
        // 事件委托
        boxEl.onclick = function (event) {
        console.log("事件委托", event.target.textContent);
        };
        // mouseover 支持事件委托
        boxEl.onmouseover = function (event) {
        console.log("onmouseover => 事件委托", event.target.textContent);
        };
        </script>
        </body>
        </html>

  • 常见的键盘事件

    属性 描述
    onkeydown 某个键盘按键被按下
    onkeypress 某个键盘按键被按下
    onkeyup 某个键盘按键被松开
    • 事件的执行顺序onkeydown、onkeypress、onkeyup

      • down 事件先发生
      • press 发生在文本被输入
      • up 发生在文本输入完成
    • 我们可以通过key code 来区分按下的键

      • code:“按键代码”

      • key

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        event.key
        event.code

        var inputEl = document.querySelector("input");
        inputEl.onkeyup = function (event) {
        if (event.code == "Enter") {
        console.log("进行搜索: ", inputEl.value);
        }
        };


        按键监听
      • 按下指定键获取焦点

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        // code
        document.onkeyup = function (event) {
        if (event.code == "KeyS") {
        inputEl.focus();
        }
        };

        // key
        document.onkeyup = function (event) {
        console.log(event.code, event.key);
        if (event.key == "S".toLowerCase()) {
        inputEl.focus();
        }
        };
  • 常见的表单事件

    属性 描述
    onchange 该事件在表单元素的内容改变时触发(input、keygen、select、textarea)
    oninput 元素获取用户输入时触发
    onfocus 元素获取焦点时触发
    onblur 元素失去焦点时触发
    onreset 表单重置时触发
    onsubmit 表单提交时触发
  • 文档加载事件

    1
    2
    3
    4
    5
    6
    7
    8
    // 注册事件监听 文档内容加载完毕 图片未加载完毕时执行 
    // 浏览器已经完全加载了 HTML,并构建了 DOM 树,但像 和样式表之类的外部资源可能尚未加载完成
    window.addEventListener("DOMContentLoaded", function () {});

    // 所有资源加载完毕时执行
    window.onload = function () {
    var divEl = document.querySelector(".box");
    };
  • window 定时器方法

    • setTimeout 允许我们将函数推迟到一段时间间隔之后再执行

    • setInterval 允许我们重复运行一个函数,从一段时间间隔之后开始运行,之后以该时间间隔连续重复运行该函数

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      var num = 10;

      // 间隔输出,仅一次
      setTimeout(() => {
      console.log("setTimeout: ", (num += num));
      }, 2000);

      // 持续输出
      setInterval(() => {
      console.log("setInterval: ", (num += num));
      }, 2000);

      区别
  • 消息轮播

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    <!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>消息轮播</title>
    <style>
    .tip-bar {
    display: inline-flex;
    flex-direction: row;
    align-items: center;
    height: 30px;
    background-color: rgba(0, 0, 0, 0.4);
    border-radius: 16px;
    }
    img {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    margin-right: 5px;
    }
    span {
    width: 250px;
    font-size: 13px;
    color: #fff;
    margin-right: 8px;
    /* 文本超出显示省略号 */
    overflow: hidden;
    /* 溢出用省略号显示 */
    text-overflow: ellipsis;
    /* 溢出不换行 */
    white-space: nowrap;
    }
    </style>
    </head>
    <body>
    <div class="tip-bar">
    <img src="./avator.jpg" alt="" />
    <span>xxx***xxx对这件商品很感兴趣</span>
    </div>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <script>
    let tipList = [
    {
    icon: "https://img95.699pic.com/photo/40094/7630.jpg_wh300.jpg",
    title: "",
    },
    {
    icon: "https://img95.699pic.com/photo/40094/7630.jpg_wh300.jpg",
    title: "",
    },
    {
    icon: "https://img95.699pic.com/photo/40094/7630.jpg_wh300.jpg",
    title: "",
    },
    ];
    // rgihdrm0kslojqvm|WnhrK251TWlUUThqaVFWbG5OeGQwdz09
    axios
    .get(
    "https://www.mxnzp.com/api/jokes/list?page=1&app_id=&app_secret="
    )
    .then((res) => {
    console.log(res);
    tipList[0].title = res.data.data.list[0].content;
    tipList[1].title = res.data.data.list[1].content;
    tipList[2].title = res.data.data.list[2].content;
    });
    // 获取元素
    var tipBar = document.querySelector(".tip-bar");
    var imgEl = document.querySelector("img");
    var spanEl = document.querySelector("span");

    // 动态切换数据 3s 切换一次数据
    var currentIndex = 0;
    setInterval(() => {
    var tipItem = tipList[currentIndex];

    imgEl.src = tipItem.icon;
    spanEl.textContent = tipItem.title;
    currentIndex++;
    if (currentIndex === tipList.length) {
    currentIndex = 0;
    }
    }, 3000);
    console.log(tipList);
    </script>
    </body>
    </html>

    消息轮播
  • 关闭隐藏

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    <!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>
    .top-bar {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 45px;
    width: 375px;
    background-color: black;
    /* 关键 */
    overflow: hidden;
    transition: all 0.3s ease-out;
    }
    .delete {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    height: 100%;
    width: 30px;
    cursor: pointer;
    }
    .delete img {
    height: 10px;
    width: 10px;
    }
    .logo {
    height: 30px;
    width: 30px;
    margin-left: 3px;
    margin-right: 30px;
    cursor: pointer;
    }
    span {
    color: #fff;
    font-size: 14px;
    flex: 1;

    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    }
    .btn {
    width: 94px;
    height: 100%;
    line-height: 45px;
    text-align: center;
    font-size: 14px;
    color: #fff;
    background-color: #f63515;
    }
    </style>
    </head>
    <body>
    <div class="top-bar">
    <div class="delete"><img src="avator.jpg" alt="" /></div>
    <img class="logo" src="avator.jpg" alt="" />
    <span>打开京东App,购物更轻松</span>
    <div class="btn">立即打开</div>
    </div>

    <script>
    var topBarEl = document.querySelector(".top-bar");
    var deleteEl = topBarEl.querySelector(".delete");
    deleteEl.onclick = function () {
    topBarEl.style.height = 0;
    };
    // 监听过渡动画结束
    topBarEl.ontransitioned = function () {
    console.log("动画执行结束................");
    topBarEl.remove();
    };
    </script>
    </body>
    </html>

  • 侧边栏展示

    1
    2
    // 使用 mouseover | mouseout 事件委托(支持冒泡)

  • 轮播图

    1
    2
    // 可迭代对象转换为 数组
    Array.from();

BOM

  • 浏览器对象模型

  • 简称BOM 由浏览器提供的用于处理文档之外的所有内容的其他对象

  • BOM 主要包括以下对象模型

    • window: 包括全局属性、方法、控制浏览器窗口相关的属性、方法
    • location: 浏览器来年街道对象的位置(URL)
    • history:操作浏览器的历史
  • window

    • location

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      <button>测试 assign</button>
      <script>
      var btn = document.querySelector("button");
      btn.onclick = function () {
      // 赋值一个新的 URL,并且跳转到 该 URL 中
      location.assign("https://www.baidu.com");
      // 打开一个新的 URL 并且跳转到 URL 中(不会再浏览器中留下记录)
      location.replace("https://www.baidu.com");
      // 重新加载页面,可以传入一个 Boolean 类型
      location.reload("https://www.baidu.com");
      };
      </script>
    • URLSearchParams

      • 可以将一个字符串转换成URLSearchParams 类型

      • 也可以将URLSearchParams 类型转换成字符串

        1
        2
        3
        4
        var urlSearchString = "?name=lisi&age=18";
        var urlParams = new URLSearchParams(urlSearchString);
        // lisi
        console.log(urlParams.get("name"));
      • 常见方法

        • get 获取搜索参数的值
        • set 设置一个新的搜索参数值
        • append 追加一个搜索参数和值
        • haspa判断是否有某个搜索和值
    • history

      • back() 返回上一页,等价于history.go(-1)
      • forward 前进下一页,等价于history.go(1)
      • go() 加载历史中的某一页
      • pushState 打开一个指定的地址
      • replaceState 打开一个新的地址,并且使用replace
      1
      2
      3
      4
      5
      6
      // 前端路由核心,修改 URL,不发生刷新
      var btn = document.querySelector("button");
      btn.onclick = function () {
      console.log("click.........");
      history.pushState({ name: "lisi" }, "", "/info");
      };
  • JSON

    • JSON 序列化

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22

      <body>
      <button>测试 replace</button>
      <script>
      var obj = {
      name: "lisi",
      age: 20,
      info: {
      state: "student",
      },
      };
      // 序列化
      var objJsonString = JSON.stringify(obj);
      localStorage.setItem("info", objJsonString);
      // 反序列化
      var json = JSON.parse(localStorage.getItem("info"));
      // {name: 'lisi', age: 20, info: {…}}
      console.log(json);
      </script>
      </body>


    • stringify

      1
      2
      // space=4(便于阅读 4 空格)
      JSON.stringify(obj,fn,4);
    • parse

      1
      JSON.parse(obj,fn(key,value),4);