JavaScript之web APIs 日期对象 DOM节点操作 M端事件

65 阅读3分钟

日期对象

实例化

使用new关键字,该操作称为实例化

   //获得当前时间 
   const date = new Date()
   //获得指定时间
   const date = new Date('2023-02-01 08:00:00')

日期对象方法

截屏2023-04-26 22.03.59.png

    <div></div>
  <script>
      const div = document.querySelector('div')
      function getMyDate(){
          const date = new Date()
          let h = date.getHours()
          let m = date.getMinutes()
          let s = date.getSeconds()
          h = h < 10 ? '0' + h : h
          m = m < 10 ? '0' + m : m
          s = s < 10 ? '0' + s : s
          return `${date.getFullYear()}${date.getMonth() + 1 }${date.getDate()}${h}:${m}:${s}` 
      }
      div.innerHTML = getMyDate()
      setInterval(function(){
        div.innerHTML = getMyDate()
      },1000)

  </script>

2.获取当前日期的方法

      const date = new Date()
      console.log(date.toLocaleString()) //2023/4/27 10:31:03
      console.log(date.toLocaleDateString()) //2023/4/27
      console.log(date.toLocaleTimeString())  //10:31:03
      console.log(date.toDateString()) //Thu Apr 27 2023

时间戳

从1970年01月01日 00:00:00起自现在的毫秒数,特殊计量时间的方式

使用场景:倒计时效果

1.使用getTime()

       const date = new Date()
       console.log(date.getTime())

2.简写+new Date() 既能返回当前时间戳,又能返回指定时间戳

    console.log(Date.now())  //返回时间戳
    const arr = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六']
    console.log(arr[new Date().getDay()]); //星期四

3.使用Date.now()

    console.log(+new Date())

案例 -- 倒计时效果和页面颜色随机更换

截屏2023-04-27 12.38.33.png

<!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>
        .box{
            width: 300px;
            height: 300px;
            background-color: brown;
            color: #fff;
            text-align: center;
            line-height: 1;
            overflow: hidden;
        }
        .next{
            font-size: 16px;
            margin: 25px 0 14px;
        }
        .title{
            font-size: 34px;
        }
        .box .clock span{
            width: 34px;
            height: 34px;
            border-radius: 2px;
            background-color: #303430;
        }
        .box .clock{
            width: 142px;
            margin: 18px auto 0;
            overflow: hidden;
        }
        .box .clock span,
        .box .clock  i{
             display: block;
             text-align: center;
             line-height: 34px;
             font-size: 23px;
             float: left;
        }
        .clock  i{
            width: 20px;
            font-style: normal;
        }
        .tips{
            margin-top: 80px;
            font-size: 23px;
        }
    </style>
</head>
<body>
    <div class="box">
        <p class="next"></p>
        <p class="title">下班倒计时</p>
        <p class="clock">
            <span id="hour"></span>
            <i>:</i>
            <span id="minutes"></span>
            <i>:</i>
            <span id="second"></span>
        </p>
        <p class="tips">18:30:00下班</p>
    </div>
    <script>
        const next = document.querySelector('.next')
        const box = document.querySelector('.box')
        //YYYY年MM月DD日
        function getMyDate(){
          const date = new Date()
          return `${date.getFullYear()}${date.getMonth() + 1 }${date.getDate()}日` 
        }
        next.innerHTML = `今天是${getMyDate()}`
        
        //倒计时效果 用将来时间戳 - 当前时间戳 /1000 再将秒数转换为时分秒
        function getCountTime(){
        const future = +new Date(`${new Date().getFullYear()} ${new Date().getMonth() + 1 } ${new Date().getDate()} 18:30:00`)
        const now = +new Date()
        //时间戳单位毫秒数 先转换为秒
        const t = (future - now) / 1000
        // let d = parseInt(t/60/60/24)
        let h = parseInt(t/60/60%24)
        let m = parseInt(t/60%60)
        let s = parseInt(t%60)
        h=h<10?'0'+h:h
        m=m<10?'0'+m:m
        s=s<10?'0'+s:s

        document.querySelector('#hour').innerHTML= h
        document.querySelector('#minutes').innerHTML= m
        document.querySelector('#second').innerHTML =s
        }
       //需将函数先调用一次 防止区域倒计时空白
        getCountTime()
        //开启定时器 
        setInterval(getCountTime,1000)

        //定时器2秒随机生成页面颜色
        function getRandomColor(flag=true){
                 if(flag){
               // 随机生成0-f之间的#ffffff 16进制颜色格式
                    let str = '#'
           let arr =['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
                    for(let i=0;i<6;i++){
                        let random = Math.floor(Math.random()*arr.length)
                        //累加6位元素
                        str += arr[random]
                    }
                    return str
                }else{  
                    // 随机生成rgb颜色
                    let r = Math.floor(Math.random()*(255+1))
                    let g = Math.floor(Math.random()*(255+1))
                    let b = Math.floor(Math.random()*(255+1))
                    return `rgb(${r},${g},${b})`
                }
             }
             

         box.style.backgroundColor  = getRandomColor() 
         setInterval(function(){
            box.style.backgroundColor  = getRandomColor() 
         },2000)
    </script>
</body>
</html>

节点操作

DOM节点

DOM树里的每一个节点都称为DOM节点

截屏2023-04-27 12.51.17.png

节点类型

元素节点:所有的标签 如body div a p; html是根节点

属性节点:所有的属性 如class id href src

文本节点:所有的文本

节点操作

节点查增删

查找节点

根据节点关系查找 : 父节点,子节点,兄弟节点

父节点: 返回为最近一级的父节点,找不到返回为null

子元素.parentNode

<style>
        .father{
            width: 300px;
            height: 300px;
            background-color: brown;
        }
        .son{
            width: 44px;
            height: 24px;
            border: 1px solid #000;
            color: azure;
            background-color: pink;
            text-align: center;
            /* font-size: 30px; */
            float: right;
        }
        p{
            text-align: center;
            color: #fff;
            font-size: 50px;
        }
    </style>
</head>
<body>
    <div class="grandpa">
        <div class="father">
            <div class="son">关掉☓</div>
            <p>我是广告</p>
        </div>
    </div>
    <script>
        const son = document.querySelector('.son')
        son.addEventListener('click',function(){
        //查找父节点
            this.parentNode.style.display = 'none'
        })
    </script>

案例 -- 关闭多个相同窗口 获取对应的父元素关闭

 <div class="grandpa">
        <div class="father">
            <div class="son">关掉☓</div>
            <p>我是广告</p>
        </div>
    </div>
    <div class="grandpa">
        <div class="father">
            <div class="son">关掉☓</div>
            <p>我是广告</p>
        </div>
    </div>
    <div class="grandpa">
        <div class="father">
            <div class="son">关掉☓</div>
            <p>我是广告</p>
        </div>
    </div>
    <script>
        const son = document.querySelectorAll('.son')
        for(let i = 0;i<son.length;i++){
            son[i].addEventListener('click',function(){
            this.parentNode.style.display = 'none'
        })
        }
    </script>

子节点:获得所有元素节点,返回一个伪数组

父元素.children

        const ul = document.querySelector('ul')
        console.log(ul.children);

兄弟节点 :

兄弟元素.previousElementSibling / 兄弟元素.nextElementSibling

       const lis = document.querySelector('li:nth-child(2)')
         console.log(lis.previousElementSibling) //上一个兄弟节点
         console.log(lis.nextElementSibling) //下一个兄弟节点

增加节点 ****

增加节点的步骤:1.创建新的节点;2.将新的节点追加到指定元素的内部

创建节点

document.createElement('标签名')

追加节点

追加到父元素的最后一个子元素

父元素.appendChild(要插入的元素)

追加到父元素中某个子元素的前面

父元素.insertBefore(要插入的元素,在哪个元素的前面)

       const ul = document.createElement('ul')
        document.body.appendChild(ul)
        const li = document.createElement('li')
        ul.appendChild(li)
        li.innerHTML = '我是第一个li'
        const li1 = document.createElement('li')
        //追击到ul的第一个
        ul.insertBefore(li1,ul.children[0])
        li1.innerHTML = '我是新追加的'

克隆节点:复制一个原有节点,追加到指定元素的内部

元素.cloneNode(布尔值) //若为true,

    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <script>
       //const li =  document.querySelector('li.first-child')
       //1.获取元素
       const ul = document.querySelector('ul')
       //2.克隆节点
       const clone = ul.children[0].cloneNode(true)
       //3.追加节点
       ul.appendChild(clone)
    </script>

删除节点

必须通过父元素删除子元素,如不存在父子关系则无法删除

父元素.removeChild(要删除的元素)

      const ul = document.querySelector('ul')
       ul.removeChild(ul.children[0])

移动端事件

触屏事件 touch

截屏2023-04-27 16.10.51.png

  const div = document.querySelector('div')
      div.addEventListener('touchstart',function(){
        console.log('触屏事件正在触发');
      })
      div.addEventListener('touchend',function(){
        console.log('手指离开了屏幕');
      })
      div.addEventListener('touchmove',function(){
        console.log('手指一直移动');
      })

js插件

轮播图插件 www.swiper.com.cn/