# BOM浏览器对象模型---一系列对象构成,提供了方法和属性

image-20220717144903257

image-20220717145017686

BOM比DOM更大,包含了DOM

全局变量和全局函数 都会变成window对象的属性和方法,调用时省略window

window下的一个特殊属性:window.name

# 4.3 window对象常见事件

# window.onload():窗口加载事件, 页面全部加载完才执行里面的代码

image-20220717145944304

# document.addEventListener('DOMContentLoaded',function(){})

image-20220717150103245

load:等页面内容全部加载完毕,包含DOM元素,图片 flash,css等

DOMContentLoaded:是DOM加载完毕,不包括图片 flash,css等,加载速度比load快一些

# 4.3.2调整窗口大小事件

window.onresize

image-20220717150612830

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    div {
        width: 200px;
        height: 200px;
        background-color: pink;
    }
</style>
<body>
        <div></div>
        <script>
                var div=document.querySelector('div')
                window.addEventListener('resize',function (){
                    console.log(window.innerWidth)
                    if (window.innerWidth<800){
                        div.style.display='none'
                    }else{
                        div.style.display='block'
                    }
                })
        </script>
</body>
</html>

# 4.4 定时器(重点)

window提供了2个非常好用的方法

  • setTimeout()
  • setInterval()

window.setTimeout(调用函数,【延迟的毫米数】)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
        // 语法规范:window.setTimeout(调用函数,延迟时间)
        // 调用时window可以使用
        //这个延迟时间单位是毫毛,如果省略默认是0
        //这个调用函数,可以直接写函数,还可以写函数名
        //页面可能有很多的定时器,经常给定时器加名字
        var time1= setTimeout(callback,3000)
        var time2= setTimeout(callback,5000)

        function  callback(){
            console.log("爆炸了")
        }
</script>
</body>
</html>

# 4.4.1 回调函数 ---(回头调用)案例自动关闭的广告

//自动关闭的广告
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<img src="../img/ad.jpg" alt="">
<script>
  var ad=document.querySelector('img')
  setTimeout(function (){
      ad.style.display='none'
  },5000)
</script>
</body>
</html>

# 4.4.2 停止setTimeout()定时器

window.cleanTimeout(定时器名字)

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
<button>点击停止定时器</button>
<script>
  var btn = document.querySelector('button');
  var timer = setTimeout(function() {
    console.log('爆炸了');

  }, 5000);
  btn.addEventListener('click', function() {
    clearTimeout(timer);
  })
</script>
</body>

</html>

4.4.3window.setInterval(调用函数,【延迟的毫米数】)

image-20220717153204483

# 案例:倒计时效果

image-20220717154006427

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            margin: 200px;
        }

        span {
            display: inline-block;
            width: 40px;
            height: 40px;
            background-color: #333;
            font-size: 20px;
            color: #fff;
            text-align: center;
            line-height: 40px;
        }
    </style>
</head>

<body>
<div>
    <span class="hour">1</span>
    <span class="minute">2</span>
    <span class="second">3</span>
</div>
<script>
    var hour=document.querySelector('.hour')
    var minute=document.querySelector('.minute')
    var second=document.querySelector('.second')
    var inputTime=+new Date("2022-7-17 18:00:00") //返回的是用户输入时间总的毫秒数
    calTime()
    setInterval(calTime,1000)
    function calTime(){
        var now=+new Date()//返回的是当前时间总的毫秒数
        var times=(inputTime-now)/1000; //times是剩余时间总的秒数
        var h=parseInt(times / 60/ 60 %24) //时
        h=h<10?'0'+h:h
        hour.innerHTML=h
        var m=parseInt(times/60%60) //分
       m= m<10?'0'+m:m
        minute.innerHTML=m
        var s=parseInt(times%60) //秒
       s= s<10?'0'+s:s
        second.innerHTML=s
    }
</script>
</body>

</html>

# 4.4.3 停止setTimeout()定时器

window.cleanInterval(定时器名字)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <button class="begin">开启定时器</button>
    <button class="stop">停止定时器</button>
    <script>
        var begin = document.querySelector('.begin');
        var stop = document.querySelector('.stop');
        var timer = null; // 全局变量  null是一个空对象
        begin.addEventListener('click', function() {
            timer = setInterval(function() {
                console.log('ni hao ma');

            }, 1000);
        })
        stop.addEventListener('click', function() {
            clearInterval(timer);
        })
    </script>
</body>

</html>

# 案例:发送短信案例

image-20220717160154156

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<style>
    div {
        margin:200px
    }
</style>
<div>手机号码:
  <input type="text" name="" id="">
  <button>发送</button>
</div>
        <script>
            var btn=document.querySelector('button')
            var time=10;
            btn.addEventListener('click',function (){
                btn.disabled=true
              var timer=  setInterval(function (){
                    if (time==0){
                        btn.disabled=false
                        btn.innerHTML='发送验证码'
                    }else{
                        btn.innerHTML=time+'秒后可重新发送'
                        time--
                    }
                },1000)
            })

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

# 4.4 this的指向问题

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <button>点击</button>
    <script>
        // this 指向问题 一般情况下this的最终指向的是那个调用它的对象

// 1. 全局作用域或者普通函数中this指向全局对象window( 注意定时器里面的this指向window)
        console.log(this);

        function fn() {
            console.log(this);

        }
        window.fn();
        window.setTimeout(function() {
            console.log(this);

        }, 1000);
// 2. 方法调用中谁调用this指向谁
        var o = {
            sayHi: function() {
                console.log(this); // this指向的是 o 这个对象

            }
        }
        o.sayHi();
        var btn = document.querySelector('button');
        // btn.onclick = function() {
        //     console.log(this); // this指向的是btn这个按钮对象

        // }
        btn.addEventListener('click', function() {
                console.log(this); // this指向的是btn这个按钮对象

            })
// 3. 构造函数中this指向构造函数的实例
        function Fun() {
            console.log(this); // this 指向的是fun 实例对象

        }
        var fun = new Fun();//使用new时,创建了一个空对象,this指向了这个空对象,因为这个空对象又赋值给了fun,所以this指向了fun这个实例对象
    </script>
</body>

</html>

# 4.5 JS执行队列 JavaScript特点:单线程的,同一时间只能做一件事

# 4.5.1H5 允许js出现多线程,js就出现了同步和异步

image-20220718135247884

# 4.5.2同步和异步的执行机制

同步任务:同步任务都在主线程上执行,形成一个执行栈

异步任务:js的异步任务是通过回调函数实现的。

一般而言,异步任务有以下三个类型:

  • 普通事件:click,resize 等
  • 资源加载:load,error等
  • 定时器:serTimeout ,setInterval等

异步任务相关的回调函数添加到任务队列中(消息队列)

image-20220718140034798

1.先执行执行栈中的同步任务(主车道)

2.异步任务(回调函数)放入任务队列中(应急车道)

3.一旦执行栈中的所有同步任务执行完毕,系统就会按次序读取任务队列中的异步任务,于是被读取的异步任务结束等待状态,进入执行栈,开始执行

image-20220718141110701

# 4.6 location对象常见属性 ---获取或设置窗体的url,解析url

# 4.6.1 url--统一资源定位符,唯一

image-20220718141426324

# 4.6.2 location 属性和方法

重点:href和search

image-20220718141537901

# 案例:5秒钟后自动跳转页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
  div {
      margin: 100px 300px;
      font-size: 25px;
      color: #999999;
  }
</style>
<body>
<div></div>
<script>
    var div=document.querySelector('div')
    var timer=5;
    dao();
    setInterval(dao,1000);
    function  dao(){
        if (timer==0){
            location.href='https://www.apipost.cn/?baidu/Swagger/ad'
        }else{
            div.innerHTML='您将在'+timer+'后跳转到首页'
            timer--;
        }

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

# 4.6.3 获取url参数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="index.html">
<!--    表单必须有name才能提交-->
    用户名:<input type="text" name="username" id="">
    <input type="submit" value="登录">
</form>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h4>首页</h4>
            <div></div>
            <script>
                var div=document.querySelector('div')
                console.log(location.search)
                //substring(param1,param2) 表示从param1开始截取调param2 如果param2不写,则截取到最后
                var params=location.search.substring(1)
                console.log(params)
                //split() 将给定的字符串按给定的参数作为分隔符 分割成数组
                var array=params.split('=')
                console.log(array)
                div.innerHTML=array[1]+"欢迎您"
            </script>
</body>
</html>

# 4.6.4 location常见方法

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <button>点击</button>
    <script>
        var btn = document.querySelector('button');
        btn.addEventListener('click', function() {
            // 记录浏览历史,所以可以实现后退功能
            // location.assign('http://www.itcast.cn');
            // 不记录浏览历史,所以不可以实现后退功能
            // location.replace('http://www.itcast.cn');
            //参数为true。相当于ctrl+f5 强制刷新,如果参数为空,则为普通刷新
            location.reload(true);
        })
    </script>
</body>

</html>

# 4.7 navigator对象

navigator.userAgent:获取是否为pc端,浏览器的信息....

<script>
    if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
        window.location.href = "../H5/index.html"; //手机
    }
</script>

# 4.8 history 对象

<script>
    var btn = document.querySelector('button');
    btn.addEventListener('click', function() {
        // history.forward();
        history.go(1);
    })
</script>
<script>
    var btn = document.querySelector('button');
    btn.addEventListener('click', function() {
        // history.back();
        history.go(-1);
    })
</script>

# 5.0 PC端网页特效

# 5.1 offset 元素偏移量系列

image-20220718150555459

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        .father {
            /* position: relative; */
            width: 200px;
            height: 200px;
            background-color: pink;
            margin: 150px;
        }
        
        .son {
            width: 100px;
            height: 100px;
            background-color: purple;
            margin-left: 45px;
        }
        
        .w {
            height: 200px;
            background-color: skyblue;
            margin: 0 auto 200px;
            padding: 10px;
            border: 15px solid red;
        }
    </style>
</head>

<body>
    <div class="father">
        <div class="son"></div>
    </div>
    <div class="w"></div>
    <script>
        // offset 系列
        var father = document.querySelector('.father');
        var son = document.querySelector('.son');
        // 1.可以得到元素的偏移 位置 返回的不带单位的数值  
        console.log(father.offsetTop);
        console.log(father.offsetLeft);
        // 它以带有定位的父亲为准  如果么有父亲或者父亲没有定位 则以 body 为准
        console.log(son.offsetLeft);
        var w = document.querySelector('.w');
        // 2.可以得到元素的大小 宽度和高度 是包含padding + border + width 
        console.log(w.offsetWidth);
        console.log(w.offsetHeight);
        // 3. 返回带有定位的父亲 否则返回的是body
        console.log(son.offsetParent); // 返回带有定位的父亲 否则返回的是body
        console.log(son.parentNode); // 返回父亲 是最近一级的父亲 亲爸爸 不管父亲有没有定位
    </script>
</body>

</html>

# 5.2 offset和style区别

image-20220718151537331

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .box {
            width: 200px;
            height: 200px;
            background-color: pink;
            padding: 10px;
        }
    </style>
</head>

<body>
    <div class="box" style="width: 200px;"></div>
    <script>
        // offset与style的区别
        var box = document.querySelector('.box');
        console.log(box.offsetWidth);
        console.log(box.style.width);
        // box.offsetWidth = '300px';
        box.style.width = '300px';
    </script>
</body>

</html>

# 案例:获取鼠标在盒子的坐标

<!DOCTYPE html>
<html lang="en">

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

<body>
    <div class="box"></div>
    <script>
        // 我们在盒子内点击, 想要得到鼠标距离盒子左右的距离。
        // 首先得到鼠标在页面中的坐标( e.pageX, e.pageY)
        // 其次得到盒子在页面中的距离(box.offsetLeft, box.offsetTop)
        // 用鼠标距离页面的坐标减去盒子在页面中的距离, 得到 鼠标在盒子内的坐标
        var box = document.querySelector('.box');
        box.addEventListener('mousemove', function(e) {
            // console.log(e.pageX);
            // console.log(e.pageY);
            // console.log(box.offsetLeft);
            var x = e.pageX - this.offsetLeft;
            var y = e.pageY - this.offsetTop;
            this.innerHTML = 'x坐标是' + x + ' y坐标是' + y;
        })
    </script>
</body>

</html>

# 案例:拖动的模态框

<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .login-header {
            width: 100%;
            text-align: center;
            height: 30px;
            font-size: 24px;
            line-height: 30px;
        }
        
        ul,
        li,
        ol,
        dl,
        dt,
        dd,
        div,
        p,
        span,
        h1,
        h2,
        h3,
        h4,
        h5,
        h6,
        a {
            padding: 0px;
            margin: 0px;
        }
        
        .login {
            display: none;
            width: 512px;
            height: 280px;
            position: fixed;
            border: #ebebeb solid 1px;
            left: 50%;
            top: 50%;
            background: #ffffff;
            box-shadow: 0px 0px 20px #ddd;
            z-index: 9999;
            transform: translate(-50%, -50%);
        }
        
        .login-title {
            width: 100%;
            margin: 10px 0px 0px 0px;
            text-align: center;
            line-height: 40px;
            height: 40px;
            font-size: 18px;
            position: relative;
            cursor: move;
        }
        
        .login-input-content {
            margin-top: 20px;
        }
        
        .login-button {
            width: 50%;
            margin: 30px auto 0px auto;
            line-height: 40px;
            font-size: 14px;
            border: #ebebeb 1px solid;
            text-align: center;
        }
        
        .login-bg {
            display: none;
            width: 100%;
            height: 100%;
            position: fixed;
            top: 0px;
            left: 0px;
            background: rgba(0, 0, 0, .3);
        }
        
        a {
            text-decoration: none;
            color: #000000;
        }
        
        .login-button a {
            display: block;
        }
        
        .login-input input.list-input {
            float: left;
            line-height: 35px;
            height: 35px;
            width: 350px;
            border: #ebebeb 1px solid;
            text-indent: 5px;
        }
        
        .login-input {
            overflow: hidden;
            margin: 0px 0px 20px 0px;
        }
        
        .login-input label {
            float: left;
            width: 90px;
            padding-right: 10px;
            text-align: right;
            line-height: 35px;
            height: 35px;
            font-size: 14px;
        }
        
        .login-title span {
            position: absolute;
            font-size: 12px;
            right: -20px;
            top: -30px;
            background: #ffffff;
            border: #ebebeb solid 1px;
            width: 40px;
            height: 40px;
            border-radius: 20px;
        }
    </style>
</head>

<body>
    <div class="login-header"><a id="link" href="javascript:;">点击,弹出登录框</a></div>
    <div id="login" class="login">
        <div id="title" class="login-title">登录会员
            <span><a id="closeBtn" href="javascript:void(0);" class="close-login">关闭</a></span>
        </div>
        <div class="login-input-content">
            <div class="login-input">
                <label>用户名:</label>
                <input type="text" placeholder="请输入用户名" name="info[username]" id="username" class="list-input">
            </div>
            <div class="login-input">
                <label>登录密码:</label>
                <input type="password" placeholder="请输入登录密码" name="info[password]" id="password" class="list-input">
            </div>
        </div>
        <div id="loginBtn" class="login-button"><a href="javascript:void(0);" id="login-button-submit">登录会员</a></div>
    </div>
    <!-- 遮盖层 -->
    <div id="bg" class="login-bg"></div>
    <script>
        //1.获取元素
        var link=document.querySelector('#link');
        var login=document.querySelector('#login');
        var closeBtn=document.querySelector('#closeBtn')
        var bg=document.querySelector('#bg')
        var title=document.querySelector('#title')
        //点击登录框时,显示登录页面和遮罩层
        link.addEventListener('click',function (){
            login.style.display='block'
            bg.style.display='block'
        })
        //点击关闭按钮时,隐藏登录页面和遮罩层
        closeBtn.addEventListener('click',function (){
            login.style.display='none'
            bg.style.display='none'
        })
        //拖动效果
        //(1)获取鼠标在盒子的位置的坐标
        title.addEventListener('mousedown',function (e) {
            var x=e.pageX-login.offsetLeft
            var y=e.pageY-login.offsetTop
            //(2)获取盒子的位置的left 和top
            document.addEventListener('mousemove',move)
            function  move(e){
                    login.style.left=e.pageX-x +'px'
                    login.style.top=e.pageY-y +'px'
            }
            //(3)当鼠标松开时,解除鼠标移动事件
            document.addEventListener('mouseup',function () {
                document.removeEventListener('mousemove',move)
            })
        })
    </script>
</body>

</html>

# 案例:仿京东的放大镜效果

image-20220718165916428

js代码

window.addEventListener('load',function (){
    //1.获取事件源
    var preview_img=document.querySelector('.preview_img')
    var mask=document.querySelector('.mask')
    var big=document.querySelector('.big')
    //2. 当鼠标经过时,mask和big显示,离开时,mask和big隐藏
    preview_img.addEventListener('mouseover',function (){
        mask.style.display='block'
        big.style.display='block'
    })
    preview_img.addEventListener('mouseout',function (){
        mask.style.display='none'
        big.style.display='none'
    })
    // 2. 黄色盒子跟着鼠标移动
    preview_img.addEventListener('mousemove',function (e) {
        var x=e.pageX-this.offsetLeft
        var y=e.pageY-this.offsetTop
        //盒子高度的一半是150
        var maskX=x-mask.offsetWidth/2
        if (maskX<=0){
            maskX=0
        }else if (maskX>=this.offsetWidth-mask.offsetWidth){
            maskX=this.offsetWidth-mask.offsetWidth
        }
        var maskY=y-mask.offsetHeight/2
        if (maskY<=0){
            maskY=0
        }else if (maskY>=this.offsetHeight-mask.offsetHeight){
            maskY=this.offsetHeight-mask.offsetHeight
        }
        mask.style.left=maskX+'px'
        mask.style.top=maskY+'px'

        //鼠标移动时,大图片跟着移动
        var bigImg=document.querySelector('.bigImg')
        var big=document.querySelector('.big')
        //大图片移动距离=遮挡层移动距离*大图片最大移动距离/遮挡层最大移动距离
        //遮挡层移动距离 maskX maskY
        //遮挡层最大移动距离
        var maxMask=preview_img.offsetWidth-mask.offsetWidth

        //大图片最大移动距离
        var bigMax=bigImg.offsetWidth-big.offsetWidth

        var  bigMaxX=maskX*bigMax/maxMask

        var  bigMaxY=maskY*bigMax/maxMask

        bigImg.style.left=-bigMaxX+'px'

        bigImg.style.top=-bigMaxY+'px'
    })
})

# 5.3 元素的可视区client系列

image-20220719113959598

clientWidth和offsetWidth最大的区别就是不包含边框

# 案例:淘宝flexible.js源码分析

立即执行函数:(function 【functionname】(){})() 不需要调用,立马能够自己执行的函数

作用:创建一个独立的作用域,避免命名冲突问题

写法:function(){})()第二个小括号看成是调用函数,可以传参,里面的变量都是局部变量

image-20220719114824407

多个立即执行函数之间,用“‘;”号隔开

三种情况会刷新页面都会触发load事件

  • a标签的超链接
  • F5或刷新按钮(强制刷新)
  • 前进后退按钮
  • image-20220719134830112
(function flexible(window, document) {
    // 获取的html 的根元素
    var docEl = document.documentElement
        // dpr 物理像素比
    var dpr = window.devicePixelRatio || 1

    // adjust body font size  设置我们body 的字体大小
    function setBodyFontSize() {
        // 如果页面中有body 这个元素 就设置body的字体大小
        if (document.body) {
            document.body.style.fontSize = (12 * dpr) + 'px'
        } else {
            // 如果页面中没有body 这个元素,则等着 我们页面主要的DOM元素加载完毕再去设置body
            // 的字体大小
            document.addEventListener('DOMContentLoaded', setBodyFontSize)
        }
    }
    setBodyFontSize();

    // set 1rem = viewWidth / 10    设置我们html 元素的文字大小
    function setRemUnit() {
        var rem = docEl.clientWidth / 10
        docEl.style.fontSize = rem + 'px'
    }

    setRemUnit()

    // reset rem unit on page resize  当我们页面尺寸大小发生变化的时候,要重新设置下rem 的大小
    window.addEventListener('resize', setRemUnit)
        // pageshow 是我们重新加载页面触发的事件
    window.addEventListener('pageshow', function(e) {
        // e.persisted 返回的是true 就是说如果这个页面是从缓存取过来的页面,也需要从新计算一下rem 的大小
        if (e.persisted) {
            setRemUnit()
        }
    })

    // detect 0.5px supports  有些移动端的浏览器不支持0.5像素的写法
    if (dpr >= 2) {
        var fakeBody = document.createElement('body')
        var testElement = document.createElement('div')
        testElement.style.border = '.5px solid transparent'
        fakeBody.appendChild(testElement)
        docEl.appendChild(fakeBody)
        if (testElement.offsetHeight === 1) {
            docEl.classList.add('hairlines')
        }
        docEl.removeChild(fakeBody)
    }
}(window, document))

# 5.4 元素滚动scroll系列

image-20220719135117204

image-20220719135159949

# 5.4.2 页面被卷去的头部

滚动条在滚动时会触发onscroll事件

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            width: 200px;
            height: 200px;
            background-color: pink;
            border: 10px solid red;
            padding: 10px;
            overflow: auto;
        }
    </style>
</head>

<body>
    <div>
        我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容 我是内容
    </div>
    <script>
        // scroll 系列
        var div = document.querySelector('div');
        console.log(div.scrollHeight);
        console.log(div.clientHeight);
        // scroll滚动事件当我们滚动条发生变化会触发的事件
        div.addEventListener('scroll', function() {
            console.log(div.scrollTop);

        })
    </script>
</body>

</html>

案例:仿淘宝右侧固定侧边栏

image-20220719140050146

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .slider-bar {
            position: absolute;
            left: 50%;
            top: 300px;
            margin-left: 600px;
            width: 45px;
            height: 130px;
            background-color: pink;
        }
        
        .w {
            width: 1200px;
            margin: 10px auto;
        }
        
        .header {
            height: 150px;
            background-color: purple;
        }
        
        .banner {
            height: 250px;
            background-color: skyblue;
        }
        
        .main {
            height: 1000px;
            background-color: yellowgreen;
        }
        
        span {
            display: none;
            position: absolute;
            bottom: 0;
        }
    </style>
</head>

<body>
    <div class="slider-bar">
        <span class="goBack">返回顶部</span>
    </div>
    <div class="header w">头部区域</div>
    <div class="banner w">banner区域</div>
    <div class="main w">主体部分</div>
    <script>
        //1. 获取元素
        var sliderbar = document.querySelector('.slider-bar');
        var banner = document.querySelector('.banner');
        // banner.offestTop 就是被卷去头部的大小 一定要写到滚动的外面
        var bannerTop = banner.offsetTop
            // 当我们侧边栏固定定位之后应该变化的数值
        var sliderbarTop = sliderbar.offsetTop - bannerTop;
        // 获取main 主体元素
        var main = document.querySelector('.main');
        var goBack = document.querySelector('.goBack');
        var mainTop = main.offsetTop;
        // 2. 页面滚动事件 scroll
        document.addEventListener('scroll', function() {
            // console.log(11);
            // window.pageYOffset 页面被卷去的头部
            // console.log(window.pageYOffset);
            // 3 .当我们页面被卷去的头部大于等于了 172 此时 侧边栏就要改为固定定位
            if (window.pageYOffset >= bannerTop) {
                sliderbar.style.position = 'fixed';
                sliderbar.style.top = sliderbarTop + 'px';
            } else {
                sliderbar.style.position = 'absolute';
                sliderbar.style.top = '300px';
            }
            // 4. 当我们页面滚动到main盒子,就显示 goback模块
            if (window.pageYOffset >= mainTop) {
                goBack.style.display = 'block';
            } else {
                goBack.style.display = 'none';
            }

        })
             //点击返回顶部
        goBack.addEventListener('click',function (){
            document.body.scrollTop = 0;
            document.documentElement.scrollTop = 0;
        })
    </script>
</body>

</html>

# 总结三大系列

  • offset系列:经常用于获得元素位置 offsetLeft offsetTop
  • client 经常用于获取元素大小 clientWidth clientHeight
  • scroll经常用于获取滚动距离 scrollTop scrollLeft
  • 注意页面滚动的距离通过window.pageXoffset 获得

# 面试题:mouseenter 和mouseover的区别

image-20220719143554417

# 5.5动画函数封装

# 5.5.1 原理:通过定时器不断移动盒子的位置

  1. 获得盒子当前的位置

  2. 让盒子在当前的位置加上一个移动距离

  3. 利用定时器不断重复这个操作

  4. 加一个结束定时器的操作

  5. 注意此元素需要添加定位,才能使用element.style.left

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <style>
        div {
            position:absolute;
            top: 0;
            left: 0;
            width: 200px;
            height: 200px;
            background-color: pink;
        }
    </style>
    <body>
            <div></div>
            <script>
                var div=document.querySelector('div')
                    var timer=  setInterval(function () {
                        if (div.offsetLeft>=document.documentElement.offsetWidth-div.clientWidth){
                            clearInterval(timer)
                        }
                        div.style.left=div.offsetLeft+5+'px'
                    },30)
    
            </script>
    </body>
    
    
    </html>
    

# 5.5.2动画函数的封装 2个参数:动画对象,移动到的距离

function  animate(obj,target){
    var timer=  setInterval(function () {
        if (obj.offsetLeft>=target){
            clearInterval(timer)
        }
        obj.style.left=obj.offsetLeft+5+'px'
    },30)
}          function  animate(obj,target){
                var timer=  setInterval(function () {
                    if (obj.offsetLeft>=target){
                        clearInterval(timer)
                    }
                    obj.style.left=obj.offsetLeft+5+'px'
                },30)
            }

# 5.5.3 不同的元素记录不同的定时器

function  animate(obj,target){
    //timer是obj的属性
     obj.timer=  setInterval(function () {
        if (obj.offsetLeft>=target){
            clearInterval(obj.timer)
        }
        obj.style.left=obj.offsetLeft+5+'px'
    },30)
}

完美方案

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<style>
    div {
        position:absolute;
        top: 0;
        left: 0;
        width: 200px;
        height: 200px;
        background-color: pink;
    }
    span {
        position: absolute;
        top: 100px;
        left: 0;
        width: 150px;
        height: 150px;
        background-color: purple;
    }
</style>
<body>
        <button>点击span才走</button>
        <div>div</div>
        <span>span</span>
        <script>
            function  animate(obj,target){
                //当不断点击按钮,元素运动速度越来越快,因为开启了太多的定时器
                //解决方案就是,让我们元素只有一个定时器执行就行
                //先清除以前的定时器,只保留当前的定时器
                clearInterval(obj.timer)
                 obj.timer=  setInterval(function () {
                    if (obj.offsetLeft>=target){
                        clearInterval(timer)
                    }
                    obj.style.left=obj.offsetLeft+5+'px'
                },30)
            }
            var div=document.querySelector('div')
            var span=document.querySelector('span')
            var btn=document.querySelector('button')
            //调用函数
            animate(div,300)
            btn.addEventListener('click',function (){
                animate(span,300)
            })



        </script>
</body>


</html>

# 5.6 缓动动画

----让元素的运动速度有所变化,最常见的是让速度慢慢停下来

  1. 让盒子每次移动的距离慢慢变小,速度就会慢慢落下来
  2. 核心算法:(目标值-现在的位置)/10(可变) 得出每次移动的步长
  3. 停止的条件是:让目前的盒子位置等于目标位置就停止定时器

# 5.6.1 缓动动画代码实现

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<style>
    div {
        position:absolute;
        top: 0;
        left: 0;
        width: 200px;
        height: 200px;
        background-color: pink;
    }
    span {
        position: absolute;
        top: 100px;
        left: 0;
        width: 150px;
        height: 150px;
        background-color: purple;
    }
</style>
<body>
        <button>点击span才走</button>
        <div>div</div>
        <span>span</span>
        <script>
            function  animate(obj,target){
                //当不断点击按钮,元素运动速度越来越快,因为开启了太多的定时器
                //解决方案就是,让我们元素只有一个定时器执行就行
                //先清除以前的定时器,只保留当前的定时器
                clearInterval(obj.timer)
                 obj.timer=  setInterval(function () {
                     //步长值 写在定时器里面
                        var step=(target-obj.offsetLeft)/10
                    if (obj.offsetLeft===target){
                        clearInterval(timer)
                    }
                    //把每次加1这个步长值改为一个慢慢变小的值    步长公式:(目标值-现在的位置)/10
                    obj.style.left=obj.offsetLeft+step+'px'
                },15)
            }
            var div=document.querySelector('div')
            var span=document.querySelector('span')
            var btn=document.querySelector('button')
            //调用函数
            animate(div,300)
            btn.addEventListener('click',function (){
                animate(span,500)
            })
                //匀速动画:盒子当前的位置+固定的值
                //缓动动画:盒子当前的位置+变化的值((目标值-现在的位置)/10)
        </script>
</body>


</html>

# 5.6.2 动画函数在多个目标值直接移动

  1. 如果是正值,则步长往大了取整
  2. 如果是负值,则步长往小了取整

# 5.6.3 动画函数添加回调函数

image-20220720174158640

回调函数写在定时器结束的位置

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<style>
    div {
        position:absolute;
        top: 0;
        left: 0;
        width: 200px;
        height: 200px;
        background-color: pink;
    }
    span {
        position: absolute;
        top: 100px;
        left: 0;
        width: 150px;
        height: 150px;
        background-color: purple;
    }
</style>
<body>
        <button class="btn500">btn500</button>
        <button class="btn800">btn800</button>
<!--        <div>div</div>-->
        <span>span</span>
        <script>
            function  animate(obj,target,callback){
                console.log(callback)
                //执行了callback=function(){}的操作
                //当不断点击按钮,元素运动速度越来越快,因为开启了太多的定时器
                //解决方案就是,让我们元素只有一个定时器执行就行
                //先清除以前的定时器,只保留当前的定时器
                clearInterval(obj.timer)
                 obj.timer=  setInterval(function () {
                     //步长值 写在定时器里面
                     //把步长值改成整数,不要出现小数的问题,往上取整
                     //    var step=Math.ceil(Math.abs((target-obj.offsetLeft))/10)
                     var step=(target-obj.offsetLeft)/10;
                    step= step>0?Math.ceil(step):Math.floor(step)
                    if (obj.offsetLeft==target){
                        clearInterval(obj.timer)
                        if (callback){
                            callback();
                        }
                    }
                    //把每次加1这个步长值改为一个慢慢变小的值    步长公式:(目标值-现在的位置)/10
                    obj.style.left=obj.offsetLeft+step+'px'
                },15)
            }
            var div=document.querySelector('div')
            var span=document.querySelector('span')
            var btn500=document.querySelector('.btn500')
            var btn800=document.querySelector('.btn800')
            //调用函数
            // animate(div,300)
            btn500.addEventListener('click',function (){
                animate(span,500,function (){
                    span.style.backgroundColor='red';
                })
            })
            btn800.addEventListener('click',function (){
                animate(span,800)
            })
                //匀速动画:盒子当前的位置+固定的值
                //缓动动画:盒子当前的位置+变化的值((目标值-现在的位置)/10)
        </script>
</body>


</html>

# 5.6.4 动画函数封装到js文件中(京东案例)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .sliderbar {
            position: fixed;
            right: 0;
            bottom: 100px;
            width: 40px;
            height: 40px;
            text-align: center;
            line-height: 40px;
            cursor: pointer;
            color: #fff;
        }
        
        .con {
            position: absolute;
            left: 0;
            top: 0;
            width: 200px;
            height: 40px;
            background-color: purple;
            z-index: -1;
        }
    </style>
    <script src="animate.js"></script>
</head>

<body>
    <div class="sliderbar">
        <span></span>
        <div class="con">问题反馈</div>
    </div>

    <script>
        // 1. 获取元素
        var sliderbar = document.querySelector('.sliderbar');
        var con = document.querySelector('.con');
        // 当我们鼠标经过 sliderbar 就会让 con这个盒子滑动到左侧
        // 当我们鼠标离开 sliderbar 就会让 con这个盒子滑动到右侧
        sliderbar.addEventListener('mouseenter', function() {
            // animate(obj, target, callback);
            animate(con, -160, function() {
                // 当我们动画执行完毕,就把 ← 改为 →
                sliderbar.children[0].innerHTML = '→';
            });

        })
        sliderbar.addEventListener('mouseleave', function() {
            // animate(obj, target, callback);
            animate(con, 0, function() {
                sliderbar.children[0].innerHTML = '←';
            });

        })
    </script>
</body>

</html>

# 5.7 网页轮播图

# 5.8 节流阀

防止轮播图按钮连续点击造成播放过快

目的:当上一个函数动画内容执行完毕,再去执行下一个函数动画,让时间无法连续触发

image-20220721141659467

window.addEventListener('load', function() {
    // 1. 获取元素
    var arrow_l = document.querySelector('.arrow-l');
    var arrow_r = document.querySelector('.arrow-r');
    var focus = document.querySelector('.focus');
    var focusWidth = focus.offsetWidth;
    // 2. 鼠标经过focus 就显示隐藏左右按钮
    focus.addEventListener('mouseenter', function() {
        arrow_l.style.display = 'block';
        arrow_r.style.display = 'block';
        clearInterval(timer);
        timer = null; // 清除定时器变量
    });
    focus.addEventListener('mouseleave', function() {
        arrow_l.style.display = 'none';
        arrow_r.style.display = 'none';
        timer = setInterval(function() {
            //手动调用点击事件
            arrow_r.click();
        }, 2000);
    });
    // 3. 动态生成小圆圈  有几张图片,我就生成几个小圆圈
    var ul = focus.querySelector('ul');
    var ol = focus.querySelector('.circle');
    // console.log(ul.children.length);
    for (var i = 0; i < ul.children.length; i++) {
        // 创建一个小li 
        var li = document.createElement('li');
        // 记录当前小圆圈的索引号 通过自定义属性来做 
        li.setAttribute('index', i);
        // 把小li插入到ol 里面
        ol.appendChild(li);
        // 4. 小圆圈的排他思想 我们可以直接在生成小圆圈的同时直接绑定点击事件
        li.addEventListener('click', function() {
            // 干掉所有人 把所有的小li 清除 current 类名
            for (var i = 0; i < ol.children.length; i++) {
                ol.children[i].className = '';
            }
            // 留下我自己  当前的小li 设置current 类名
            this.className = 'current';
            // 5. 点击小圆圈,移动图片 当然移动的是 ul 
            // ul 的移动距离 小圆圈的索引号 乘以 图片的宽度 注意是负值
            // 当我们点击了某个小li 就拿到当前小li 的索引号
            var index = this.getAttribute('index');
            // 当我们点击了某个小li 就要把这个li 的索引号给 num  
            num = index;
            // 当我们点击了某个小li 就要把这个li 的索引号给 circle  
            circle = index;
            // num = circle = index;
            console.log(focusWidth);
            console.log(index);

            animate(ul, -index * focusWidth);
        })
    }
    // 把ol里面的第一个小li设置类名为 current
    ol.children[0].className = 'current';
    // 6. 克隆第一张图片(li)放到ul 最后面
    var first = ul.children[0].cloneNode(true);
    ul.appendChild(first);
    // 7. 点击右侧按钮, 图片滚动一张
    var num = 0;
    // circle 控制小圆圈的播放
    var circle = 0;
    // flag 节流阀
    var flag = true;
    arrow_r.addEventListener('click', function() {
        if (flag) {
            flag = false; // 关闭节流阀
            // 如果走到了最后复制的一张图片,此时 我们的ul 要快速复原 left 改为 0
            if (num == ul.children.length - 1) {
                ul.style.left = 0;
                num = 0;
            }
            num++;
            animate(ul, -num * focusWidth, function() {
                flag = true; // 打开节流阀
            });
            // 8. 点击右侧按钮,小圆圈跟随一起变化 可以再声明一个变量控制小圆圈的播放
            circle++;
            // 如果circle == 4 说明走到最后我们克隆的这张图片了 我们就复原
            if (circle == ol.children.length) {
                circle = 0;
            }
            // 调用函数
            circleChange();
        }
    });

    // 9. 左侧按钮做法
    arrow_l.addEventListener('click', function() {
        if (flag) {
            flag = false;
            if (num == 0) {
                num = ul.children.length - 1;
                ul.style.left = -num * focusWidth + 'px';

            }
            num--;
            animate(ul, -num * focusWidth, function() {
                flag = true;
            });
            // 点击左侧按钮,小圆圈跟随一起变化 可以再声明一个变量控制小圆圈的播放
            circle--;
            // 如果circle < 0  说明第一张图片,则小圆圈要改为第4个小圆圈(3)
            // if (circle < 0) {
            //     circle = ol.children.length - 1;
            // }
            circle = circle < 0 ? ol.children.length - 1 : circle;
            // 调用函数
            circleChange();
        }
    });

    function circleChange() {
        // 先清除其余小圆圈的current类名
        for (var i = 0; i < ol.children.length; i++) {
            ol.children[i].className = '';
        }
        // 留下当前的小圆圈的current类名
        ol.children[circle].className = 'current';
    }
    // 10. 自动播放轮播图
    var timer = setInterval(function() {
        //手动调用点击事件
        arrow_r.click();
    }, 2000);

})

# 案例:返回顶部

把我们的窗口滚动到指定的位置

window.scroll(x,y)

加动画的滚动

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .slider-bar {
            position: absolute;
            left: 50%;
            top: 300px;
            margin-left: 600px;
            width: 45px;
            height: 130px;
            background-color: pink;
        }
        
        .w {
            width: 1200px;
            margin: 10px auto;
        }
        
        .header {
            height: 150px;
            background-color: purple;
        }
        
        .banner {
            height: 250px;
            background-color: skyblue;
        }
        
        .main {
            height: 1000px;
            background-color: yellowgreen;
        }
        
        span {
            display: none;
            position: absolute;
            bottom: 0;
        }
    </style>
</head>

<body>
    <div class="slider-bar">
        <span class="goBack">返回顶部</span>
    </div>
    <div class="header w">头部区域</div>
    <div class="banner w">banner区域</div>
    <div class="main w">主体部分</div>
    <script>
        var sliderBar=document.querySelector('.slider-bar')
        var banner=document.querySelector('.banner')
        var bannerTop=banner.offsetTop
        var sliderBarTop=sliderBar.offsetTop
        var sliderTop=sliderBarTop-bannerTop
        var main=document.querySelector('.main')
        var mainTop=main.offsetTop
        var goBack=document.querySelector('.goBack')
        document.addEventListener('scroll',function (){
                if (window.pageYOffset>=bannerTop){
                    sliderBar.style.position='fixed';
                    sliderBar.style.top=sliderTop+"px"
                }else{
                    sliderBar.style.position='absolute';
                    sliderBar.style.top='300px'
                }
            if (window.pageYOffset>=mainTop){
                goBack.style.display='block'
            }else{
                goBack.style.display='none'
            }
        })
        //点击返回顶部
        goBack.addEventListener('click',function (){
            //里面的x,y不跟单位,直接写数字
            //     window.scroll(0,0)
            animate(window,0)
            //加了动画的滚动
        })
        function  animate(obj,target,callback){
            console.log(callback)
            //执行了callback=function(){}的操作
            //当不断点击按钮,元素运动速度越来越快,因为开启了太多的定时器
            //解决方案就是,让我们元素只有一个定时器执行就行
            //先清除以前的定时器,只保留当前的定时器
            clearInterval(obj.timer)
            obj.timer=  setInterval(function () {
                //步长值 写在定时器里面
                //把步长值改成整数,不要出现小数的问题,往上取整
                //    var step=Math.ceil(Math.abs((target-obj.offsetLeft))/10)
                var step=(target-obj.pageYOffset)/10;
                step= step>0?Math.ceil(step):Math.floor(step)
                if (obj.pageYOffset==target){
                    clearInterval(obj.timer)
                    if (callback){
                        callback();
                    }
                }
                //把每次加1这个步长值改为一个慢慢变小的值    步长公式:(目标值-现在的位置)/10
                // obj.style.left=obj.offsetLeft+step+'px'
                window.scroll(0,obj.pageYOffset+step)
            },15)
        }
    </script>
</body>

</html>

# 案例:筋斗云案例

image-20220721144437186

<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0
        }
        
        ul {
            list-style: none;
        }
        
        body {
            background-color: black;
        }
        
        .c-nav {
            width: 900px;
            height: 42px;
            background: #fff url(images/rss.png) no-repeat right center;
            margin: 100px auto;
            border-radius: 5px;
            position: relative;
        }
        
        .c-nav ul {
            position: absolute;
        }
        
        .c-nav li {
            float: left;
            width: 83px;
            text-align: center;
            line-height: 42px;
        }
        
        .c-nav li a {
            color: #333;
            text-decoration: none;
            display: inline-block;
            height: 42px;
        }
        
        .c-nav li a:hover {
            color: white;
        }
        
        .c-nav li.current a {
            color: #0dff1d;
        }
        
        .cloud {
            position: absolute;
            left: 0;
            top: 0;
            width: 83px;
            height: 42px;
            background: url(images/cloud.gif) no-repeat;
        }
    </style>
    <script src="animate.js"></script>
    <script>
        window.addEventListener('load', function() {
            // 1. 获取元素
            var cloud = document.querySelector('.cloud');
            var c_nav = document.querySelector('.c-nav');
            var lis = c_nav.querySelectorAll('li');
            // 2. 给所有的小li绑定事件 
            // 这个current 做为筋斗云的起始位置
            var current = 0;
            for (var i = 0; i < lis.length; i++) {
                // (1) 鼠标经过把当前小li 的位置做为目标值
                lis[i].addEventListener('mouseenter', function() {
                    animate(cloud, this.offsetLeft);
                });
                // (2) 鼠标离开就回到起始的位置 
                lis[i].addEventListener('mouseleave', function() {
                    animate(cloud, current);
                });
                // (3) 当我们鼠标点击,就把当前位置做为目标值
                lis[i].addEventListener('click', function() {
                    current = this.offsetLeft;
                });
            }
        })
    </script>
</head>

<body>
    <div id="c_nav" class="c-nav">
        <span class="cloud"></span>
        <ul>
            <li class="current"><a href="#">首页新闻</a></li>
            <li><a href="#">师资力量</a></li>
            <li><a href="#">活动策划</a></li>
            <li><a href="#">企业文化</a></li>
            <li><a href="#">招聘信息</a></li>
            <li><a href="#">公司简介</a></li>
            <li><a href="#">我是佩奇</a></li>
            <li><a href="#">啥是佩奇</a></li>
        </ul>
    </div>
</body>

</html>

# 5.9 移动端网页特效

# 5.9.1 触屏事件(touch)

触屏touch事件 说明
touchstart 手指触摸到一个DOM元素时触发
touchmove 手指在一个DOM元素上滑动时触发
touchend 手指在一个DOM元素上移开时触发
<script>
    // 1. 获取元素
    // 2. 手指触摸DOM元素事件
    var div = document.querySelector('div');
    div.addEventListener('touchstart', function() {
        console.log('我摸了你');

    });
    // 3. 手指在DOM元素身上移动事件
    div.addEventListener('touchmove', function() {
        console.log('我继续摸');

    });
    // 4. 手指离开DOM元素事件
    div.addEventListener('touchend', function() {
        console.log('轻轻的我走了');

    });
</script>

# 5.9.2 触摸事件对象(TouchEvent)

<script>
    // 触摸事件对象
    // 1. 获取元素
    // 2. 手指触摸DOM元素事件
    var div = document.querySelector('div');
    div.addEventListener('touchstart', function(e) {
        // console.log(e);
        // touches 正在触摸屏幕的所有手指的列表 
        // targetTouches 正在触摸当前DOM元素的手指列表
        // 如果侦听的是一个DOM元素,他们两个是一样的
        // changedTouches 手指状态发生了改变的列表 从无到有 或者 从有到无
        // 因为我们一般都是触摸元素 所以最经常使用的是 targetTouches
        console.log(e.targetTouches[0]);
        // targetTouches[0] 就可以得到正在触摸dom元素的第一个手指的相关信息比如 手指的坐标等等


    });
    // 3. 手指在DOM元素身上移动事件
    div.addEventListener('touchmove', function() {


    });
    // 4. 手指离开DOM元素事件
    div.addEventListener('touchend', function(e) {
        // console.log(e);
        // 当我们手指离开屏幕的时候,就没有了 touches 和 targetTouches 列表
        // 但是会有 changedTouches


    });
</script>

# 5.9.3 移动端拖动元素

  1. touchstart touchmove touchend 可以实现拖动元素
  2. 拖动元素需要当前手指的坐标值 我们可以使用 targetTouches[0] 里面的pageX和pageY
  3. 移动端拖动的原理:手指移动中,计算出手指移动的距离。用盒子原来的位置+手指移动的距离
  4. 手指移动的距离:手指滑动后的位置减去手指刚开始触摸的位置

拖动元素三步曲:

(1)触摸元素touchstart:获取手指初始坐标,同时获得盒子原来的位置

(2)移动手指touchmove:计算手指的滑动距离,并且移动盒子

(3)离开手指touched

注意:手指移动也会触发滚动屏幕所以这里要阻止默认的屏幕滚动 e.preventDefault()

<script>
    var div=document.querySelector('div')
    var startX=0; //鼠标的起始位置
    var startY=0;
    var x=0; //盒子的起始位置
    var y=0;
    div.addEventListener('touchstart',function (e){
        //当鼠标点击时,获取鼠标的起始坐标以及盒子的位置
        startX=e.targetTouches[0].pageX; //获取到鼠标的起始位置
        startY=e.targetTouches[0].pageY;
        x=this.offsetLeft;   //盒子的起始位置
        y=this.offsetTop;
    })
    div.addEventListener('touchmove',function (e) {
        //计算鼠标的移动距离
        var moveX=e.targetTouches[0].pageX-startX;
        var moveY=e.targetTouches[0].pageY-startY;
        //盒子的移动距离:盒子起始的位置+鼠标的移动距离
        this.style.left= x + moveX+'px';
        this.style.top= y + moveY+'px';
    })
</script>

# 6.0 移动端常见特效

知识点:

监听过渡完成事件:transitionend

classList:返回元素的类名,以数组的形式存储

添加类名:是在后面添加类名,不会覆盖以前的类名,注意前面不需要加小点

element.classList.add('类名')

删除类名:

element.classList.remove('类名')

切换类名:

element.classList.toggle('类名')

window.addEventListener('load', function() {
    // alert(1);
    // 1. 获取元素 
    var focus = document.querySelector('.focus');
    var ul = focus.children[0];
    // 获得focus 的宽度
    var w = focus.offsetWidth;
    var ol = focus.children[1];
    // 2. 利用定时器自动轮播图图片
    var index = 0;
    var timer = setInterval(function() {
        index++;
        var translatex = -index * w;
        ul.style.transition = 'all .3s';
        ul.style.transform = 'translateX(' + translatex + 'px)';
    }, 2000);
    // 等着我们过渡完成之后,再去判断 监听过渡完成的事件 transitionend 
    ul.addEventListener('transitionend', function() {
        // 无缝滚动
        if (index >= 3) {
            index = 0;
            // console.log(index);
            // 去掉过渡效果 这样让我们的ul 快速的跳到目标位置
            ul.style.transition = 'none';
            // 利用最新的索引号乘以宽度 去滚动图片
            var translatex = -index * w;
            ul.style.transform = 'translateX(' + translatex + 'px)';
        } else if (index < 0) {
            index = 2;
            ul.style.transition = 'none';
            // 利用最新的索引号乘以宽度 去滚动图片
            var translatex = -index * w;
            ul.style.transform = 'translateX(' + translatex + 'px)';
        }
        // 3. 小圆点跟随变化
        // 把ol里面li带有current类名的选出来去掉类名 remove
        ol.querySelector('.current').classList.remove('current');
        // 让当前索引号 的小li 加上 current   add
        ol.children[index].classList.add('current');
    });

    // 4. 手指拖动轮播图 
    // 触摸元素 touchstart: 获取手指初始坐标
    var startX = 0;
    var moveX = 0; // 后面我们会使用这个移动距离所以要定义一个全局变量
    var flag = false;
    ul.addEventListener('touchstart', function(e) {
        startX = e.targetTouches[0].pageX;
        // 手指触摸的时候就停止定时器
        clearInterval(timer);
    });
    // 移动手指 touchmove: 计算手指的滑动距离, 并且移动盒子
    ul.addEventListener('touchmove', function(e) {
        // 计算移动距离
        moveX = e.targetTouches[0].pageX - startX;
        // 移动盒子:  盒子原来的位置 + 手指移动的距离 
        var translatex = -index * w + moveX;
        // 手指拖动的时候,不需要动画效果所以要取消过渡效果
        ul.style.transition = 'none';
        ul.style.transform = 'translateX(' + translatex + 'px)';
        flag = true; // 如果用户手指移动过我们再去判断否则不做判断效果
        e.preventDefault(); // 阻止滚动屏幕的行为
    });
    // 手指离开 根据移动距离去判断是回弹还是播放上一张下一张
    ul.addEventListener('touchend', function(e) {
        if (flag) {
            // (1) 如果移动距离大于50像素我们就播放上一张或者下一张
            if (Math.abs(moveX) > 50) {
                // 如果是右滑就是 播放上一张 moveX 是正值
                if (moveX > 0) {
                    index--;
                } else {
                    // 如果是左滑就是 播放下一张 moveX 是负值
                    index++;
                }
                var translatex = -index * w;
                ul.style.transition = 'all .3s';
                ul.style.transform = 'translateX(' + translatex + 'px)';
            } else {
                // (2) 如果移动距离小于50像素我们就回弹
                var translatex = -index * w;
                ul.style.transition = 'all .1s';
                ul.style.transform = 'translateX(' + translatex + 'px)';
            }
        }
        // 手指离开的时候就重新开启定时器
        clearInterval(timer);
        timer = setInterval(function() {
            index++;
            var translatex = -index * w;
            ul.style.transition = 'all .3s';
            ul.style.transform = 'translateX(' + translatex + 'px)';
        }, 2000);
    });


    // 返回顶部模块制作
    var goBack = document.querySelector('.goBack');
    var nav = document.querySelector('nav');
    window.addEventListener('scroll', function() {
        if (window.pageYOffset >= nav.offsetTop) {
            goBack.style.display = 'block';
        } else {
            goBack.style.display = 'none';
        }
    });
    goBack.addEventListener('click', function() {
        window.scroll(0, 0);
    })
})

# 6.1 click延时解决方案

移动端click事件会有300ms的延时,原因是移动端屏幕双击会缩放页面

解决方案:

1.禁用缩放。<meta name="viewport", content=“user-scalable=no”>

2.利用touch事件自己封装这个事件解决300ms延迟。

原理:

  1. 当我们手指触摸屏幕,记录当前触摸时间
  2. 当我们手指离开屏幕,用离开的时间减去触摸的时间
  3. 如果时间小于150ms,并且没有滑动过屏幕,name我们就定义为点击

3.fastclick插件使用

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            width: 50px;
            height: 50px;
            background-color: pink;
        }
    </style>
    <script src="fastclick.js"></script>
</head>

<body>
    <div></div>
    <script>
        if ('addEventListener' in document) {
            document.addEventListener('DOMContentLoaded', function() {
                FastClick.attach(document.body);
            }, false);
        }
        var div = document.querySelector('div');
        div.addEventListener('click', function() {
            alert(11);
        })
    </script>
</body>

</html>

# 6.2 Swiper 插件的使用

window.addEventListener('load',function (){
    var swiper = new Swiper(".mySwiper", {
        spaceBetween: 30,
        centeredSlides: true,
        autoplay: {
            delay: 1000,
            disableOnInteraction: false,
        },
        pagination: {
            el: ".swiper-pagination",
            clickable: true,
        },
        clickable: true
    });
})

# 6.3 其他移动端常见插件

superslide:http://www.superslide2.com/

iscroll:https://github.com/cubiq/iscroll

image-20220726150446209

# 6.4 练习-移动端视频插件 zy.media.js

image-20220726151533156

# 6.5 移动端常用开发框架

前端常用的框架:Bootstrap,Vue,Angular,React。既能开发PC端,又能开发移动端。(大而全)

前端常用的移动端插件有:swiper,superslide,iscroll等。(小而专一)

# 6.6 本地存储

  1. 数据存储在用户浏览器中
  2. 设置,读取方便,甚至页面刷新不丢失数据
  3. 容量较大,sessionStorage约5M,localStorage 约20M
  4. 只能存储字符串,可以将对象JSON.stringify()编码后存储

# 6.6.1 sessionStorage

  • 生命周期为关闭服务器窗口

  • 在同一个窗口(页面)下数据可以共享。

  • 以键值对的形式存储使用。

  • 语法:

  • 存储数据:sessionStorage.setItem(key,value)

  • 获取数据:sessionStorage.getItem(key)

  • 删除数据:sessionStorage.removeItem(key)

  • 删除所有数据:sessionStorage.clear()

  • <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    
    <body>
        <input type="text">
        <button class="set">存储数据</button>
        <button class="get">获取数据</button>
        <button class="remove">删除数据</button>
        <button class="del">清空所有数据</button>
        <script>
            console.log(localStorage.getItem('username'));
    
            var ipt = document.querySelector('input');
            var set = document.querySelector('.set');
            var get = document.querySelector('.get');
            var remove = document.querySelector('.remove');
            var del = document.querySelector('.del');
            set.addEventListener('click', function() {
                // 当我们点击了之后,就可以把表单里面的值存储起来
                var val = ipt.value;
                sessionStorage.setItem('uname', val);
                sessionStorage.setItem('pwd', val);
            });
            get.addEventListener('click', function() {
                // 当我们点击了之后,就可以把表单里面的值获取过来
                console.log(sessionStorage.getItem('uname'));
    
            });
            remove.addEventListener('click', function() {
                // 
                sessionStorage.removeItem('uname');
    
            });
            del.addEventListener('click', function() {
                // 当我们点击了之后,清除所有的
                sessionStorage.clear();
    
            });
        </script>
    </body>
    
    </html>
    

# 6.6.2 localStorage

  • 生命周期为永久生效,除非手动删除,否则关闭页面也存在
  • 可以多窗口(页面)共享(同一个浏览器可以共享)
  • 以键值对的形式存储使用。
  • 语法:
  • 存储数据:localStorage.setItem(key,value)
  • 获取数据:localStorage.getItem(key)
  • 删除数据:localStorage.removeItem(key)
  • 删除所有数据:localStorage.clear()
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <input type="text">
    <button class="set">存储数据</button>
    <button class="get">获取数据</button>
    <button class="remove">删除数据</button>
    <button class="del">清空所有数据</button>
    <script>
        var ipt = document.querySelector('input');
        var set = document.querySelector('.set');
        var get = document.querySelector('.get');
        var remove = document.querySelector('.remove');
        var del = document.querySelector('.del');
        set.addEventListener('click', function() {
            var val = ipt.value;
            localStorage.setItem('username', val);
        })
        get.addEventListener('click', function() {
            console.log(localStorage.getItem('username'));

        })
        remove.addEventListener('click', function() {
            localStorage.removeItem('username');

        })
        del.addEventListener('click', function() {
            localStorage.clear();

        })
    </script>
</body>

</html>

# 案例:记住用户名

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text" name="username" id="username"><input type="checkbox" name="remember" id="remember">记住密码
<script>
        var username=document.querySelector('#username')
        var remember=document.querySelector('#remember')
        if (localStorage.getItem('username')){
            username.value=localStorage.getItem('username')
            remember.checked=true
        }
    //change事件
        remember.addEventListener('change',function () {
            if (remember.checked){
                //如果被选中则存储到localStorage中
                localStorage.setItem('username',username.value)
            }else {
                //否则 则将数据从localStorage中删除
                localStorage.removeItem('username')
            }
        })
</script>
</body>
</html>
最新更新时间: 2023/4/25 23:14:02