【DOM BOM】笔记 6 日 PC网页特效

1. 元素偏移量 offset 系列

1.1 offset 概述

我们使用offset系列相关属性可以动态地得到该元素的位置(偏移)、大小等。

  • 获得元素距离带有定位父元素的位置。
  • 获得元素自身的大小(宽度高度)。
  • 注意:返回的数值都不带单位。
offset系列属性作用
element.offsetParent返回作为该元素带有定位的父级元素,如果父级都没有定位则返回body
element.offsetTop返回元素相对带有定位父元素上方的偏移
element.offsetLeft返回元素相对带有定位父元素左边框的偏移
element.offsetWidth返回自身包括padding、边框、内容区的宽度,返回数值不带单位
element.offsetHeight返回自身包括padding、边框、内容区的高度,返回数值不带单位
<!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);  // 150
        console.log(father.offsetLeft); // 150
        // 它以带有定位的父亲为准  如果么有父亲或者父亲没有定位 则以 body 为准
        console.log(son.offsetLeft);  // 195
        var w = document.querySelector('.w');
        // 2.可以得到元素的大小 宽度和高度 是包含padding + border + width 
        console.log(w.offsetWidth);  // 
        console.log(w.offsetHeight);  // 250
        // 3. 返回带有定位的父亲 否则返回的是body
        console.log(son.offsetParent); // 返回带有定位的父亲 否则返回的是body
        console.log(son.parentNode); // 返回父亲 是最近一级的父亲 亲爸爸 不管父亲有没有定位
    </script>
</body>
</html>

1.2 offset 与 style 区别

在这里插入图片描述

<!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 login = document.querySelector('.login');
        var mask = document.querySelector('.login-bg');
        var link = document.querySelector('#link');
        var closeBtn = document.querySelector('#closeBtn');
        var title = document.querySelector('#title');
        // 2. 点击弹出层这个链接 link  让mask 和login 显示出来
        link.addEventListener('click', function() {
                mask.style.display = 'block';
                login.style.display = 'block';
            })
            // 3. 点击 closeBtn 就隐藏 mask 和 login 
        closeBtn.addEventListener('click', function() {
                mask.style.display = 'none';
                login.style.display = 'none';
            })
            // 4. 开始拖拽
            // (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>
仿京东放大镜案例

2. 元素可视区 client 系列

client 翻译过来就是客户端,我们使用 client 系列的相关属性来获取元素可视区的相关信息。通过 client 系列的相关属性可以动态的得到该元素的边框大小、元素大小。

client 系列属性作用
element.clientTop返回元素上边框的大小
element.clientLeft返回元素左边框的大小
element.clientWidth返回自身包括padding、内容区的宽度、不包含边框,返回数值不带单位
element.clientHeight返回自身包括padding、内容区的高度、不包含边框,返回数值不带单位

2.1 立即执行函数

  • 立即执行函数:(function() {})() 或者 (function(){}());,不需要调用,立马能够自己执行的函数。
  • 第二个小括号可以看作是调用函数。
  • 主要作用:创建一个独立的作用域。避免了命名冲突问题。
    <script>
        // 1.立即执行函数: 不需要调用,立马能够自己执行的函数
        function fn() {
            console.log(1);

        }
        fn();
        // 2. 写法 也可以传递参数进来
        // 1.(function() {})()    或者  2. (function(){}());
        (function(a, b) {
            console.log(a + b);
            var num = 10;
        })(1, 2); // 第二个小括号可以看做是调用函数
        (function sum(a, b) {
            console.log(a + b);
            var num = 10; // 局部变量
        }(2, 3));
        // 3. 立即执行函数最大的作用就是 独立创建了一个作用域, 里面所有的变量都是局部变量 不会有命名冲突的情况
    </script>

2.2 淘宝flexible.js源码分析

在这里插入图片描述

(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))

3. 元素滚动scroll系列

3.1 元素 scroll 系列属性

我们使用scroll系列的相关属性可以动态的得到该元素的大小、滚动距离等。
在这里插入图片描述
在这里插入图片描述

3.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>

3.3 仿淘宝固定侧边栏

在这里插入图片描述

<!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';
            }

        })
    </script>
</body>

</html>

3.4 页面被卷去的头部兼容性解决方案

需要注意的是,页面被卷去的头部,有兼容性问题,因此被卷去的头部通常有如下几种写法:

  1. 声明了DTD,使用document.documentElement.scrollTop。
  2. 未声明DTD,使用document.body.scrollTop。
  3. 新方法window.pageYOffset和window.pageXOffset,IE9开始支持。
function getScroll() {
  return {
    left: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0 , 
    top: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
};
}
// 使用的时候
getScroll().left

三大系列总结

在这里插入图片描述
在这里插入图片描述

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

mouseenter 和 mouseover的区别

mouseenter 鼠标事件
  • 当鼠标移动到元素上时就会触发 mouseenter 事件。
  • 类似 mouseover,它们两者之间的区别是:
  • mouseover 鼠标经过自身盒子会触发,经过子盒子还会触发。mouseenter 指挥经过自身盒子触发。
  • 之所以这样,就是因为mouseenter 不会冒泡。
  • 跟 mouseenter 搭配鼠标离开 mouseleave 同样不会冒泡。

4. 动画函数封装

4.1 动画实现原理

核心原理:通过定时器 setInterval() 不断移动盒子位置。
实现步骤:

  1. 获得盒子当前位置。
  2. 让盒子在当前位置加上1个移动距离。
  3. 利用定时器不断重复这个操作。
  4. 加一个结束定时器的条件。
  5. 注意此元素需要添加定位,才能使用element.style.left。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>动画原理</title>
  <style>
    div {
      position:absolute;
      left: 0;
      width: 100px;
      height: 100px;
      background-color: skyblue;
    }
  </style>
</head>
<body>
  <div></div>
  <script>
    var div = document.querySelector('div');
    var timer = setInterval(function() {
      if(div.offsetLeft >= 400) {
        // 停止动画 本质是停止定时器
        clearInterval(timer);
      }
      div.style.left = div.offsetLeft + 5 + 'px';
    },30)
    
  </script>
</body>
</html>

4.2 动画函数简单封装

注意函数需要传递 2 个参数,动画对象和移动到的距离。

<!DOCTYPE html>
<html lang="zh-CN">
  <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 {
        position: absolute;
        left: 0;
        width: 100px;
        height: 100px;
        background-color: pink;
      }

      span {
        position: absolute;
        left: 0;
        top: 200px;
        display: block;
        width: 150px;
        height: 150px;
        background-color: purple;
      }
    </style>
  </head>

  <body>
    <div></div>
    <span>夏雨荷</span>
    <script>
      // 简单动画函数封装obj目标对象 target 目标位置
      function animate(obj, target) {
        var timer = setInterval(function () {
          if (obj.offsetLeft >= target) {
            // 停止动画 本质是停止定时器
            clearInterval(timer);
          }
          obj.style.left = obj.offsetLeft + 1 + "px";
        }, 30);
      }

      var div = document.querySelector("div");
      var span = document.querySelector("span");
      // 调用函数
      animate(div, 300);
      animate(span, 200);
    </script>
  </body>
</html>

4.3 动画函数给不同元素记录不同定时器

如果多个元素都使用这个动画函数,每个都要var生命定时器。我们可以给不同的元素使用不同的定时器(自己专门用自己的定时器)。

核心原理:利用JS是一门动态语言,可以很方便的给当前对象添加属性。

<!DOCTYPE html>
<html lang="zh-CN">
  <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 {
        position: absolute;
        left: 0;
        width: 100px;
        height: 100px;
        background-color: pink;
      }

      span {
        position: absolute;
        left: 0;
        top: 200px;
        display: block;
        width: 150px;
        height: 150px;
        background-color: purple;
      }
    </style>
  </head>

  <body>
    <button>点击夏雨荷才走</button>
    <div></div>
    <span>夏雨荷</span>
    <script>
      // var obj = {};
      // obj.name = 'andy';
      // 简单动画函数封装obj目标对象 target 目标位置
      // 给不同的元素指定了不同的定时器
      function animate(obj, target) {
        // 当我们不断的点击按钮,这个元素的速度会越来越快,因为开启了太多的定时器
        // 解决方案就是 让我们元素只有一个定时器执行
        // 先清除以前的定时器,只保留当前的一个定时器执行
        clearInterval(obj.timer);
        obj.timer = setInterval(function () {
          if (obj.offsetLeft >= target) {
            // 停止动画 本质是停止定时器
            clearInterval(obj.timer);
          }
          obj.style.left = obj.offsetLeft + 1 + "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, 200);
      });
    </script>
  </body>
</html>

4.4 缓动效果原理

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

  1. 让盒子每次移动的距离慢慢变小,速度就会慢慢落下来。
  2. 核心算法:(目标值 - 现在的位置)/ 10作为每次移动的距离步长。
  3. 停止条件:当前盒子位置等于目标位置就停止定时器。
<!DOCTYPE html>
<html lang="zh-CN">
  <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 {
        position: absolute;
        left: 0;
        width: 100px;
        height: 100px;
        background-color: pink;
      }
      span {
        position: absolute;
        left: 0;
        top: 200px;
        display: block;
        width: 150px;
        height: 150px;
        background-color: purple;
      }
    </style>
  </head>

  <body>
    <button>点击夏雨荷才走</button>
    <span>夏雨荷</span>
    <script>
      // 缓动动画函数封装obj目标对象 target 目标位置
      // 思路:
      // 1. 让盒子每次移动的距离慢慢变小, 速度就会慢慢落下来。
      // 2. 核心算法:(目标值 - 现在的位置) / 10 做为每次移动的距离 步长
      // 3. 停止的条件是: 让当前盒子位置等于目标位置就停止定时器
      function animate(obj, target) {
        // 先清除以前的定时器,只保留当前的一个定时器执行
        clearInterval(obj.timer);
        obj.timer = setInterval(function () {
          // 步长值写到定时器的里面
          var step = (target - obj.offsetLeft) / 10;
          if (obj.offsetLeft == target) {
            // 停止动画 本质是停止定时器
            clearInterval(obj.timer);
          }
          // 把每次加1 这个步长值改为一个慢慢变小的值  步长公式:(目标值 - 现在的位置) / 10
          obj.style.left = obj.offsetLeft + step + "px";
        }, 15);
      }
      var span = document.querySelector("span");
      var btn = document.querySelector("button");

      btn.addEventListener("click", function () {
        // 调用函数
        animate(span, 500);
      });
      // 匀速动画 就是 盒子是当前的位置 +  固定的值 10
      // 缓动动画就是  盒子当前的位置 + 变化的值(目标值 - 现在的位置) / 10)
    </script>
  </body>
</html>

4.5 动画函数多个目标值之间移动

可以让动画函数从800 移动到500。
当我们点击按钮时候,判断步长是正值还是复制。

<!DOCTYPE html>
<html lang="zh-CN">
  <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 {
        position: absolute;
        left: 0;
        width: 100px;
        height: 100px;
        background-color: pink;
      }

      span {
        position: absolute;
        left: 0;
        top: 200px;
        display: block;
        width: 150px;
        height: 150px;
        background-color: purple;
      }
    </style>
  </head>

  <body>
    <button class="btn500">点击夏雨荷到500</button>
    <button class="btn800">点击夏雨荷到800</button>
    <span>夏雨荷</span>
    <script>
      // 缓动动画函数封装obj目标对象 target 目标位置
      // 思路:
      // 1. 让盒子每次移动的距离慢慢变小, 速度就会慢慢落下来。
      // 2. 核心算法:(目标值 - 现在的位置) / 10 做为每次移动的距离 步长
      // 3. 停止的条件是: 让当前盒子位置等于目标位置就停止定时器
      function animate(obj, target) {
        // 先清除以前的定时器,只保留当前的一个定时器执行
        clearInterval(obj.timer);
        obj.timer = setInterval(function () {
          // 步长值写到定时器的里面
          // 把我们步长值改为整数 不要出现小数的问题
          // var step = Math.ceil((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);
          }
          // 把每次加1 这个步长值改为一个慢慢变小的值  步长公式:(目标值 - 现在的位置) / 10
          obj.style.left = obj.offsetLeft + step + "px";
        }, 15);
      }
      var span = document.querySelector("span");
      var btn500 = document.querySelector(".btn500");
      var btn800 = document.querySelector(".btn800");

      btn500.addEventListener("click", function () {
        // 调用函数
        animate(span, 500);
      });
      btn800.addEventListener("click", function () {
        // 调用函数
        animate(span, 800);
      });
      // 匀速动画 就是 盒子是当前的位置 +  固定的值 10
      // 缓动动画就是  盒子当前的位置 + 变化的值(目标值 - 现在的位置) / 10)
    </script>
  </body>
</html>

4.6 动画函数添加回调函数

回调函数原理:函数可以作为一个参数。将这个函数作为参数传到另一个函数里面,当那个函数执行完之后,再执行传进去的这个函数,这个过程就叫做回调。

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

<!DOCTYPE html>
<html lang="zh-CN">
  <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 {
        position: absolute;
        left: 0;
        width: 100px;
        height: 100px;
        background-color: pink;
      }

      span {
        position: absolute;
        left: 0;
        top: 200px;
        display: block;
        width: 150px;
        height: 150px;
        background-color: purple;
      }
    </style>
  </head>

  <body>
    <button class="btn500">点击夏雨荷到500</button>
    <button class="btn800">点击夏雨荷到800</button>
    <span>夏雨荷</span>
    <script>
      // 缓动动画函数封装obj目标对象 target 目标位置
      // 思路:
      // 1. 让盒子每次移动的距离慢慢变小, 速度就会慢慢落下来。
      // 2. 核心算法:(目标值 - 现在的位置) / 10 做为每次移动的距离 步长
      // 3. 停止的条件是: 让当前盒子位置等于目标位置就停止定时器
      function animate(obj, target, callback) {
        // console.log(callback);  callback = function() {}  调用的时候 callback()

        // 先清除以前的定时器,只保留当前的一个定时器执行
        clearInterval(obj.timer);
        obj.timer = setInterval(function () {
          // 步长值写到定时器的里面
          // 把我们步长值改为整数 不要出现小数的问题
          // var step = Math.ceil((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 span = document.querySelector("span");
      var btn500 = document.querySelector(".btn500");
      var btn800 = document.querySelector(".btn800");

      btn500.addEventListener("click", function () {
        // 调用函数
        animate(span, 500);
      });
      btn800.addEventListener("click", function () {
        // 调用函数
        animate(span, 800, function () {
          // alert('你好吗');
          span.style.backgroundColor = "red";
        });
      });
      // 匀速动画 就是 盒子是当前的位置 +  固定的值 10
      // 缓动动画就是  盒子当前的位置 + 变化的值(目标值 - 现在的位置) / 10)
    </script>
  </body>
</html>

4.7 动画函数封装到单独JS文件里面

因为以后经常使用这个动画函数,可以单独封装到一个JS文件里面,使用的时候引用这个JS文件即可。

  1. 单独新建一个JS文件。
function animate(obj, target, callback) {
    // console.log(callback);  callback = function() {}  调用的时候 callback()

    // 先清除以前的定时器,只保留当前的一个定时器执行
    clearInterval(obj.timer);
    obj.timer = setInterval(function () {
      // 步长值写到定时器的里面
      // 把我们步长值改为整数 不要出现小数的问题
      // var step = Math.ceil((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);
  }
  1. 引入JS文件。
<!DOCTYPE html>
<html lang="zh-CN">
  <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. 常见网页特效案例

案例: 网页轮播图

轮播图也称为焦点图,是网页中比较常见的网页特效.
功能需求:

  1. 鼠标经过轮播图模块,左右按钮显示,离开隐藏左右按钮.
  2. 点击右侧按钮一次,图片往左播放一张,一次类推,左侧按钮同理.
  3. 图片播放的同时,下面小圆圈模块跟随一起变化.
  4. 点击小圆圈,可以播放相应的图片.
  5. 鼠标不经过轮播图,轮播图也会自动播放图片.
  6. 鼠标经过,轮播图模块,自动播放停止.

案例分析:

  • 因为JS较多,我们单独新建JS文件夹,再新建JS文件,引入页面中.
  • 此时需要添加load事件.
  • 鼠标经过轮播图模块,左右按钮显示,离开隐藏左右按钮.
  • 显示隐藏display按钮.
    在这里插入图片描述在这里插入图片描述在这里插入图片描述

在这里插入图片描述

在这里插入图片描述在这里插入图片描述
在这里插入图片描述
在这里插入图片描述在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

5.1 节流阀

防止轮播图按钮连续点击造成播放过快.
在这里插入图片描述

案例:返回顶部

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值