Web API学习笔记(六)

大小和位置相关的属性
offset

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    body {
      margin: 0;
    }
    #box {
      position: relative;
      width: 300px;
      height: 300px;
      background-color: red;
      overflow: hidden;
      margin: 50px;
    }
    #child {
      width: 100px;
      height: 100px;
      background-color: blue;
      margin: 50px;
      border: 10px solid yellow;
      padding: 10px;
    }
  </style>
</head>
<body>
  <div id="box">
    <div id="child">
      
    </div>
  </div>
  <script>
    // 3组和大小 位置相关的属性
    // offset  client  scroll
    // 
    // offset  偏移量
    // var box = document.getElementById('box');
    // // 获取box的坐标
    // console.log(box.offsetLeft);
    // console.log(box.offsetTop);
    // // 获取box的大小
    // console.log(box.offsetWidth);
    // console.log(box.offsetHeight);


    // offsetParent   获取距离当前元素最近的定位父元素,如果没有定位父元素此时是body

    // 获取子元素的位置和大小
    var child = document.getElementById('child');
    console.log(child.offsetParent);
    // 获取child的位置     offsetLeft 距离offsetParent的横向偏移
    console.log(child.offsetLeft);
    console.log(child.offsetTop);

    // 获取child的大小   包括边框和padding
    console.log(child.offsetWidth);
    console.log(child.offsetHeight);

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

client
clientLeft 是border-left 的宽度
clientTop border-top 的宽度
获取大小
clientWidth clientHeight 包括padding 但是不包括边框
offsetWidth offsetHeight 包括padding和边框

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    body {
      margin: 0;
    }

    #box {
      width: 100px;
      height: 100px;
      margin: 50px;
      border: 30px solid red;
      padding: 10px;
      background-color: green;
    }
  </style>
</head>
<body>
  <div id="box">
    
  </div>
  <script>
    // client
    var box = document.getElementById('box');
    // clientLeft  是border-left 的宽度
    // clientTop    border-top 的宽度
    console.log(box.clientLeft);
    console.log(box.clientTop);


    // 获取大小   包括padding  但是不包括边框
    console.log(box.clientWidth);
    console.log(box.clientHeight);

    // offsetWidth   offsetHeight     包括padding和边框

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

scroll

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    body {
      margin: 0;
    }

    #box {
      width: 100px;
      height: 100px;
      margin: 50px;
      border: 30px solid red;
      padding: 10px;
      background-color: green;
      overflow: auto;
    }
  </style>
</head>
<body>
  <div id="box">
    小明跟小华到动物园玩,进门时,小明指着小华对看门人说:“看清楚喔!等会儿出来,别说我偷了你们的猴子!” 
  </div>
  <script>
    // scroll
    var box = document.getElementById('box');
    // 当拖动box中的滚动条的时候触发
    box.onscroll = function () {
      console.log(box.scrollLeft);
      console.log(box.scrollTop);

    }


    // // box滚动出去的距离
    // console.log(box.scrollLeft);
    // console.log(box.scrollTop);

    // // 内容的大小,包括padding 和未显示的内容,不包括滚动条
     console.log(box.scrollWidth);
     console.log(box.scrollHeight);

    // // 元素的大小 + padding   不包括滚动条
     console.log(box.clientWidth);
     console.log(box.clientHeight);

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

获取鼠标在页面的位置,处理浏览器兼容性

function getPage(e) {
  var pageX = e.pageX || e.clientX + getScroll().scrollLeft;
  var pageY = e.pageY || e.clientY + getScroll().scrollTop;
  return {
    pageX: pageX,
    pageY: pageY
  }
}

拖拽案例

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .nav {
            height: 30px;
            background: #036663;
            border-bottom: 1px solid #369;
            line-height: 30px;
            padding-left: 30px;
        }

        .nav a {
            color: #fff;
            text-align: center;
            font-size: 14px;
            text-decoration: none;

        }

        .d-box {
            width: 400px;
            height: 300px;
            border: 5px solid #eee;
            box-shadow: 2px 2px 2px 2px #666;
            position: absolute;
            top: 40%;
            left: 40%;
            background-color: white;

            /* 不让文字被选中 */
            -webkit-user-select:none;
            -moz-user-select:none;
            -ms-user-select:none;
            user-select:none;
        }

        .hd {
            width: 100%;
            height: 25px;
            background-color: #7c9299;
            border-bottom: 1px solid #369;
            line-height: 25px;
            color: white;
            cursor: move;
        }

        #box_close {
            float: right;
            cursor: pointer;
        }
    </style>
</head>
<body>
<div class="nav">
    <a href="javascript:;" id="register">注册信息</a>
</div>
<div class="d-box" id="d_box">
    <div class="hd" id="drop">注册信息 (可以拖拽)
        <span id="box_close">【关闭】</span>
    </div>
    <div class="bd"></div>
</div>
<script src="common.js"></script>
<script>
  var box = document.getElementById('d_box');
  var drop = document.getElementById('drop');

  drop.onmousedown = function (e) {
    // 兼容性处理 
    e = e || window.event;
    // 当鼠标按下的时候,求鼠标在盒子中的位置
    // 鼠标在盒子中的位置 = 鼠标在页面上的位置 - 盒子的位置
    var x = e.pageX - box.offsetLeft;
    var y = e.pageY - box.offsetTop;

    // 鼠标在文档中移动
    document.onmousemove = function (e) {
      e = e || window.event;
      // 当鼠标在页面上移动的时候。求盒子的坐标
      // 盒子的坐标 = 鼠标当前在页面中的位置 - 鼠标在盒子中的位置
      var boxX = e.pageX - x;
      var boxY = e.pageY - y;

      box.style.left = boxX + 'px';
      box.style.top = boxY + 'px';
    }
  }

  // 当鼠标弹起的时候,移除鼠标移动事件
  document.onmouseup = function () {
    document.onmousemove = null;
  }

  // 点击关闭按钮,隐藏盒子
  var box_close = document.getElementById('box_close');
  box_close.onclick = function () {
    box.style.display = 'none';
  }
</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 {
            width: 512px;
            height: 280px;
            position: absolute;
            border: #ebebeb solid 1px;
            left: 50%;
            right: 50%;
            background: #ffffff;
            box-shadow: 0px 0px 20px #ddd;
            z-index: 9999;
            margin-left: -256px;
            margin-top: 140px;
            display: none;
        }
        .login-title {
            width: 100%;
            margin: 10px 0px 0px 0px;
            text-align: center;
            line-height: 40px;
            height: 40px;
            font-size: 18px;
            position: relative;
            cursor: move;
            -moz-user-select:none;/*火狐*/
            -webkit-user-select:none;/*webkit浏览器*/
            -ms-user-select:none;/*IE10*/
            -khtml-user-select:none;/*早期浏览器*/
            user-select:none;
        }
        .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 {
            width: 100%;
            height: 100%;
            position: fixed;
            top: 0px;
            left: 0px;
            background: #000000;
            filter: alpha(opacity=30);
            -moz-opacity: 0.3;
            -khtml-opacity: 0.3;
            opacity: 0.3;
            display: none;
        }
        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:void(0);">点击,弹出登录框</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>
  // 显示登录框和遮盖层
  var login = document.getElementById('login');
  var bg = document.getElementById('bg');
  //1 点击按钮,弹出登录框和遮盖层
  var link = document.getElementById('link');
  link.onclick = function () {
    login.style.display = 'block';
    bg.style.display = 'block';
    return false;
  }

  // 2 点击关闭按钮,隐藏 登录框和遮盖层
  var closeBtn = document.getElementById('closeBtn');
  closeBtn.onclick = function () {
    // 隐藏 登录框和遮盖层
    login.style.display = 'none';
    bg.style.display = 'none';
  }

  // 3 拖拽
  var title = document.getElementById('title');
  title.onmousedown = function (e) {
    // 鼠标按下,求鼠标在盒子中的位置
    var x = e.pageX - login.offsetLeft;
    var y = e.pageY - login.offsetTop;

    document.onmousemove = function (e) {
      // 鼠标移动的时候, 盒子的坐标
      var loginX = e.pageX - x;
      var loginY = e.pageY - y;

      login.style.left = loginX + 256 + 'px';
      login.style.top = loginY - 140 + 'px';
    }
  }

  document.onmouseup = function () {
    // 移除鼠标移动的事件
    document.onmousemove = null;
  }
</script>
</body>
</html>

放大镜案例
onmouseover鼠标经过
onmouseout 鼠标移出


<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            width: 350px;
            height: 350px;
            margin: 100px;
            border: 1px solid #ccc;
            position: relative;
        }

        .big {
            width: 400px;
            height: 400px;
            position: absolute;
            top: 0;
            left: 360px;
            border: 1px solid #ccc;
            overflow: hidden;
            display: none;
        }

        .big img {
            position: absolute;
        }

        .mask {
            width: 175px;
            height: 175px;
            background: rgba(255, 255, 0, 0.4);
            position: absolute;
            top: 0px;
            left: 0px;
            cursor: move;
            display: none;
        }

        .small {
            position: relative;
        }

    </style>
</head>
<body>
<div class="box" id="box">
    <div class="small">
        <img src="images/small.webp" width="350" alt=""/>

        <div class="mask"></div>
    </div>
    <div class="big">
        <img src="images/big.jpg" width="800" alt=""/>
    </div>
</div>
<script src="common.js"></script>
<script>
  var box = my$('box');
  var smallBox = box.children[0];
  var bigBox = box.children[1];

  var smallImage = smallBox.children[0];
  var mask = smallBox.children[1];
  var bigImage = bigBox.children[0];


  // 1 鼠标经过的时候 显示 mask和bigBox , 当鼠标离开box的时候隐藏mask和bigBox
  box.onmouseover = function () {
    // 显示 mask和bigBox 
    mask.style.display = 'block';
    bigBox.style.display = 'block'
  }

  box.onmouseout = function () {
    mask.style.display = 'none';
    bigBox.style.display = 'none';
  }

  // 2 当鼠标在盒子中移动的时候,让mask和鼠标一起移动
  box.onmousemove = function (e) {
    e = e || window.event;
    // 获取鼠标在盒子中的位置,就是mask的坐标
    var maskX = getPage(e).pageX - box.offsetLeft;
    var maskY = getPage(e).pageY - box.offsetTop;

    // 让鼠标出现在mask的中心点
    maskX = maskX - mask.offsetWidth / 2;
    maskY = maskY - mask.offsetHeight / 2;

    // 把mask限制到box中
    maskX = maskX < 0 ? 0 : maskX;
    maskY = maskY < 0 ? 0 : maskY;

    maskX = maskX > box.offsetWidth - mask.offsetWidth ? box.offsetWidth - mask.offsetWidth : maskX;
    maskY = maskY > box.offsetHeight - mask.offsetHeight ? box.offsetHeight - mask.offsetHeight : maskY;

    mask.style.left = maskX + 'px';
    mask.style.top = maskY + 'px';
    // 3 当mask移动的时候,让大图片移动
    // 求 大图片移动的距离
    
    // mask移动的距离 / mask最大能够移动的距离  = 大图片移动的距离 / 大图片最大能够移动的距离
    
    // mask最大能够移动的距离
    var maskMax = box.offsetWidth - mask.offsetWidth;
    // 大图片最大能够移动的距离
    var bigImageMax = bigImage.offsetWidth - bigBox.offsetWidth;

    var bigImageX = maskX * bigImageMax / maskMax;
    var bigImageY = maskY * bigImageMax / maskMax;

    bigImage.style.left = -bigImageX + 'px';
    bigImage.style.top = -bigImageY + 'px';
  }
  
  
</script>
</body>
</html>

onmouseenter和onmouseover 区别

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    #box1 {
      width: 300px;
      height: 300px;
      background-color: red;
    }
    #box2 {
      width: 150px;
      height: 150px;
      background-color: blue;
    }
  </style>
</head>
<body>
  <div id="box1">
    <div id="box2">
      
    </div>
  </div>
  <script>
    // mouseenter  和 mouseover的区别
    var box1 = document.getElementById('box1');
    var i = 0;
    // 触发子元素的mouseover,会冒泡到父元素上
    // box1.onmouseover = function () {
    //   i++;
    //   console.log(i);
    // }
    // 
    // 此事件不触发事件冒泡
    box1.onmouseenter = function () {
      i++;
      console.log(i);
    }
  </script>
</body>
</html>

模拟滚动条案例

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {margin: 0;padding: 0;}
        .box {
            width: 300px;
            height: 500px;
            border: 1px solid red;
            margin: 100px;
            position: relative;

            overflow: hidden;

            /* 不让文字被选中 */
            -webkit-user-select:none;
            -moz-user-select:none;
            -ms-user-select:none;
            user-select:none;
        }
        .content {
            padding: 5px 18px 5px 5px;
            position: absolute;
            top: 0;
            left: 0;

        }
        .scroll {
            width: 18px;
            height: 100%;
            position: absolute;
            top: 0;
            right: 0;
            background-color: #eee;
        }
        .bar {
            height: 100px;
            width: 100%;
            position: absolute;
            top: 0;
            left: 0;
            background-color: red;
            border-radius:  10px;
            cursor: pointer;
        }
    </style>
</head>
<body>
<div class="box" id="box">
    <div class="content" id="content">
       我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
       我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,
        我是文字内容,我是文字内容,我是文字内容,

    </div>
    <div class="scroll" id="scroll">
        <div class="bar" id="bar"></div>
    </div>
</div>
<script src="common.js"></script>
<script>
  var box = my$('box');
  var content = my$('content');
  var scroll = my$('scroll');
  var bar = my$('bar');
  //1 根据内容的大小,计算滚动条的高度
  //  滚动条的高度 / scroll的高度 = box的高度 / 内容的高度
  // offsetHeight     元素的大小 + padding + border
  // clientHeight     元素的大小 + padding
  // scrollHeight     内容的大小 + padding
  
  // 当内容的高度大于box的高度,再计算 滚动条的高度,否则的话滚动条的高度为0
  var barHeight = 0;
  if (content.scrollHeight > box.clientHeight) {
    barHeight = box.clientHeight / content.scrollHeight * scroll.clientHeight;
  }
  bar.style.height = barHeight + 'px';
  
  //2 让滚动条能够拖拽
  // 2.1 当鼠标按下的时候,求鼠标在滚动条中的位置
  bar.onmousedown = function (e) {
    e = e || window.event;

    // 鼠标在滚动条中的位置
    var y = getPage(e).pageY - bar.offsetTop - box.offsetTop;
    // 2.2 当鼠标在页面上移动的时候,求滚动条的位置
    document.onmousemove = function (e) {
        //求滚动条的位置
        var barY = getPage(e).pageY - y - box.offsetTop;

        // 控制bar不能移除scroll
        barY = barY < 0 ? 0 : barY;
        barY = barY > scroll.clientHeight - bar.clientHeight ? scroll.clientHeight - bar.clientHeight : barY;

        bar.style.top = barY + 'px';

        //3 当拖拽滚动条的时候,改变内容的位置
        
        // 内容滚动的距离 / 内容最大能够滚动的距离 = 滚动条滚动的距离 / 滚动条最大能够滚动的距离
        
        // 内容最大能够滚动的距离
        var contentMax = content.scrollHeight - box.clientHeight;
        // 滚动条最大能够滚动的距离
        var barMax = scroll.clientHeight - bar.clientHeight;

        var contentY = barY / barMax * contentMax;
        content.style.top = -contentY + 'px';
    }
  }

  document.onmouseup = function () {
    // 移除鼠标移动的事件
    document.onmousemove = null;
  }
 
</script>
</body>
</html>

动画案例

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    #box {
      position: relative;
      width: 100px;
      height: 100px;
      background-color: red;
    }
  </style>
</head>
<body>
  <input type="button" id="btn" value="动画 800">
  <input type="button" id="btn1" value="动画 400">

  <div id="box">
    
  </div>

  <script>
    var btn = document.getElementById('btn');
    var box = document.getElementById('box');

    var btn1 = document.getElementById('btn1');

 
    btn.onclick = function () {
      animate(box, 800);
    }

    btn1.onclick = function () {
      animate(box, 400);
    }
    var timerId = null;
    // 封装动画的函数
    function animate(element, target) {

       // 通过判断,保证页面上只有一个定时器在执行动画
      if (timerId) {
        clearInterval(timerId);
        timerId = null;
      }

      timerId = setInterval(function () {
        // 步进  每次移动的距离
        var step = 10;
        // 盒子当前的位置
        var current = element.offsetLeft;

        if (current >= target) {
          // 让定时器停止
          clearInterval(timerId);
          // 让盒子到target的位置
          element.style.left = target + 'px';
          return;
        }
        // 移动盒子
        current += step;
        element.style.left = current + 'px';
      }, 30);
    }
  </script>
</body>
</html>

轮播图


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        * {
            padding: 0;
            margin: 0;
            list-style: none;
            border: 0;
        }

        .all {
            width: 500px;
            height: 200px;
            padding: 7px;
            border: 1px solid #ccc;
            margin: 100px auto;
            position: relative;
        }

        .screen {
            width: 500px;
            height: 200px;
            overflow: hidden;
            position: relative;
        }

        .screen li {
            width: 500px;
            height: 200px;
            overflow: hidden;
            float: left;
        }

        .screen ul {
            position: absolute;
            left: 0;
            top: 0px;
            width: 3000px;
        }

        .all ol {
            position: absolute;
            right: 10px;
            bottom: 10px;
            line-height: 20px;
            text-align: center;
        }

        .all ol li {
            float: left;
            width: 20px;
            height: 20px;
            background: #fff;
            border: 1px solid #ccc;
            margin-left: 10px;
            cursor: pointer;
        }

        .all ol li.current {
            background: yellow;
        }

        #arr {
            display: none;
            z-index: 1000;

        }

        #arr span {
            width: 40px;
            height: 40px;
            position: absolute;
            left: 5px;
            top: 50%;
            margin-top: -20px;
            background: #000;
            cursor: pointer;
            line-height: 40px;
            text-align: center;
            font-weight: bold;
            font-family: '黑体';
            font-size: 30px;
            color: #fff;
            opacity: 0.3;
            border: 1px solid #fff;
        }

        #arr #right {
            right: 5px;
            left: auto;
        }
    </style>
</head>
<body>
<div class="all" id='box'>
    <div class="screen">
        <ul>
            <li><img src="images/wf1.jpg" width="500" height="200"/></li>
            <li><img src="images/wf2.jpg" width="500" height="200"/></li>
            <li><img src="images/wf3.jpg" width="500" height="200"/></li>
            <li><img src="images/wf4.jpg" width="500" height="200"/></li>
            <li><img src="images/wf5.jpg" width="500" height="200"/></li>
        </ul>
        <ol>
        </ol>
    </div>
    <div id="arr"><span id="left">&lt;</span><span id="right">&gt;</span></div>
</div>
<script src="common.js"></script>
<script src="animate.js"></script>
<script src="index.js"></script>
</body>
</html>

animate.js

// var timerId = null;
// 封装动画的函数
function animate(element, target) {
   // 通过判断,保证页面上只有一个定时器在执行动画
  if (element.timerId) {
    clearInterval(element.timerId);
    element.timerId = null;
  }

  element.timerId = setInterval(function () {
    // 步进  每次移动的距离
    var step = 10;
    // 盒子当前的位置
    var current = element.offsetLeft;
    // 当从400 到 800  执行动画
    // 当从800 到 400  不执行动画

    // 判断如果当前位置 > 目标位置 此时的step  要小于0
    if (current > target) {
      step = - Math.abs(step);
    }

    // Math.abs(current - target)   <= Math.abs(step)
    if (Math.abs(current - target)   <= Math.abs(step)) {
      // 让定时器停止
      clearInterval(element.timerId);
      // 让盒子到target的位置
      element.style.left = target + 'px';
      return;
    }
    // 移动盒子
    current += step;
    element.style.left = current + 'px';
  }, 5);
}

common.js

function my$(id) {
  return document.getElementById(id);
}

// 处理浏览器兼容性
// 获取第一个子元素
function getFirstElementChild(element) {
    var node, nodes = element.childNodes, i = 0;
    while (node = nodes[i++]) {
        if (node.nodeType === 1) {
            return node;
        }
    }
    return null;
}

// 处理浏览器兼容性
// 获取下一个兄弟元素
 function getNextElementSibling(element) {
    var el = element;
    while (el = el.nextSibling) {
      if (el.nodeType === 1) {
          return el;
      }
    }
    return null;
  }


// 处理innerText和textContent的兼容性问题
// 设置标签之间的内容
function setInnerText(element, content) {
  // 判断当前浏览器是否支持 innerText
  if (typeof element.innerText === 'string') {
    element.innerText = content;
  } else {
    element.textContent = content;
  }
}

// 处理注册事件的兼容性问题
// eventName, 不带on,  click  mouseover  mouseout
function addEventListener(element, eventName, fn) {
  // 判断当前浏览器是否支持addEventListener 方法
  if (element.addEventListener) {
    element.addEventListener(eventName, fn);  // 第三个参数 默认是false
  } else if (element.attachEvent) {
    element.attachEvent('on' + eventName, fn);
  } else {
    // 相当于 element.onclick = fn;
    element['on' + eventName] = fn;
  }
}

// 处理移除事件的兼容性处理
function removeEventListener(element, eventName, fn) {
  if (element.removeEventListener) {
    element.removeEventListener(eventName, fn);
  } else if (element.detachEvent) {
    element.detachEvent('on' + eventName, fn);
  } else {
    element['on' + eventName] = null;
  }
}

// 获取页面滚动距离的浏览器兼容性问题
// 获取页面滚动出去的距离
function getScroll() {
  var scrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft;
  var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  return {
    scrollLeft: scrollLeft,
    scrollTop: scrollTop
  }
}

// 获取鼠标在页面的位置,处理浏览器兼容性
function getPage(e) {
  var pageX = e.pageX || e.clientX + getScroll().scrollLeft;
  var pageY = e.pageY || e.clientY + getScroll().scrollTop;
  return {
    pageX: pageX,
    pageY: pageY
  }
}


//格式化日期对象,返回yyyy-MM-dd HH:mm:ss的形式
function formatDate(date) {
  // 判断参数date是否是日期对象
  // instanceof  instance 实例(对象)   of 的
  // console.log(date instanceof Date);
  if (!(date instanceof Date)) {
    console.error('date不是日期对象')
    return;
  }

  var year = date.getFullYear(),
      month = date.getMonth() + 1,
      day = date.getDate(),
      hour = date.getHours(),
      minute = date.getMinutes(),
      second = date.getSeconds();

  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;
  hour = hour < 10 ? '0' + hour : hour;
  minute = minute < 10 ? '0' + minute : minute;
  second = second < 10 ? '0' + second : second;

  return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
}

// 获取两个日期的时间差
function getInterval(start, end) {
  // 两个日期对象,相差的毫秒数
  var interval = end - start;
  // 求 相差的天数/小时数/分钟数/秒数
  var day, hour, minute, second;

  // 两个日期对象,相差的秒数
  // interval = interval / 1000;
  interval /= 1000;

  day = Math.round(interval / 60 / 60 / 24);
  hour = Math.round(interval / 60 / 60 % 24);
  minute = Math.round(interval / 60 % 60);
  second = Math.round(interval % 60);

  return {
    day: day,
    hour: hour,
    minute: minute,
    second: second
  }
}


index.js

 // 获取元素
  var box = my$('box');
  var screen = box.children[0];
  var ul = screen.children[0];
  var ol = screen.children[1];


  // 箭头 arrow
  var arr = my$('arr');
  var arrLeft = my$('left');
  var arrRight = my$('right');

  // 图片的宽度
  var imgWidth = screen.offsetWidth;

  // 1 动态生成序号
  // 页面上总共有多少张图片    5 没有克隆的li
  var count = ul.children.length;
  for (var i = 0; i < count; i++) {
    var li = document.createElement('li');
    ol.appendChild(li);
    setInnerText(li, i + 1);
    // 2 点击序号 动画的方式 切换图片
    li.onclick = liClick;

    // 让当前li记录他的索引
    // 设置标签的自定义属性
    li.setAttribute('index', i);
  }
  function liClick() {
    // 2.1 取消其它li的高亮显示,让当前li高亮显示
    for (var i = 0; i < ol.children.length; i++) {
      var li = ol.children[i];
      li.className = '';
    }
    // 让当前li高亮显示
    this.className = 'current';
    // 2.2 点击序号,动画的方式切换到当前点击的图片位置
    
    // 获取自定义属性
    var liIndex = parseInt(this.getAttribute('index'));
    animate(ul, -liIndex * imgWidth);

    // 全局变量index  和 li中的index保持一致
    index = liIndex;
  }
  // 让序号1高亮显示
  ol.children[0].className = 'current';

  
  // 3 鼠标放到盒子上显示箭头
  box.onmouseenter = function () {
    arr.style.display = 'block';
    // 清除定时器
    clearInterval(timerId);
  }

  box.onmouseleave = function () {
    arr.style.display = 'none';
    // 重新开启定时器
    timerId = setInterval(function () {
      arrRight.click();
    }, 2000);
  }
  // 4 实现上一张和下一张的功能
  // 下一张
  
  var index = 0; // 第一张图片的索引
  arrRight.onclick = function () {
    // 判断是否是克隆的第一张图片,如果是克隆的第一张图片,此时修改ul的坐标,显示真正的第一张图片
    if (index === count) {
      ul.style.left = '0px';
      index = 0;
    }
    // 
    // 总共有5张图片,但是还有一张克隆的图片  克隆的图片的索引是5
    // 4 < 5
    index++;
    if (index < count) {
        // animate(ul, -index * imgWidth);
        // //
        // 获取图片对应的序号,让序号点击
        ol.children[index].click();
    } else {
      //如果是最后一张图片 以动画的方式,移动到克隆的第一张图片
      animate(ul, -index * imgWidth);
      // 取消所有序号的高亮显示,让第一序号高亮显示
      for (var i = 0; i < ol.children.length; i++) {
        var li = ol.children[i];
        li.className = '';
      }
      ol.children[0].className = 'current';
    }
  }
  // 上一张
  arrLeft.onclick = function () {
    // 如果当前是第一张图片,此时要偷偷的切换到最后一张图片的位置(克隆的第一张图片)
    if (index === 0) {
      index = count;
      ul.style.left = - index * imgWidth + 'px';
    }

    index--;
    ol.children[index].click();

    // // 如果不是第一张的话 index--
    // if (index > 0) {
    //   index--;
    //   // animate(ul, -index * imgWidth);
    //   ol.children[index].click();
    // }
  }

  // 无缝滚动
  // 获取ul中的第一个li
  var firstLi = ul.children[0];
  // 克隆li  cloneNode()  复制节点  
  // 参数  true  复制节点中的内容
  //       false  只复制当前节点,不复制里面的内容
  var cloneLi = firstLi.cloneNode(true);
  ul.appendChild(cloneLi);


  // 5 自动切换图片
  var timerId = setInterval(function () {
    // 切换到下一张图片
    arrRight.click();
  }, 2000);

回到顶部案例

 .to-top {
    width: 50px;
    height: 50px;
    background-image: url(http://s.url.cn/qqun/xiaoqu/buluo/p/js/images/to_top.6a40e92f2a02f3945477ff9937f5cb20.png);
    background-repeat: no-repeat;
    background-position: 0 0;
    background-size: 50px 50px;
    cursor: pointer;
    display: none;
     position: fixed;
     bottom: 150px;
     left: 86%;
}
<div class="to-top" id="totop"></div>
// 获取元素
var bodyTop = my$('top');

// top 是window自带的一个属性,此属性是只读的。此属性默认是window对象

// 回到顶部的按钮
var totop = my$('totop');

// 当拖动滚动条的时候执行
window.onscroll = function () {
  //1 当拖动滚动条的时候,当内容滚动出去 10px的时候,改变top的高度,并且显示回到顶部按钮
  
  // 调用common.js getScroll函数,获取页面滚动出去的距离
  var scrollTop = getScroll().scrollTop;
  if (scrollTop > 10) {
    // 改变top
    bodyTop.className = 'header fixed';
    // 显示回到顶部
    totop.style.display = 'block';
  } else {
    // 改变top
    bodyTop.className = 'header';
    // 显示回到顶部
    totop.style.display = 'none';
  }


  // 如何获取滚动距离
  // document.body.scrollTop
  // documentElement  网页中的根元素 html
  // document.documentElement.scrollTop
}

//2 当点击回到顶部按钮的时候,动画的方式,回到最上面,让滚动距离为0
var timerId = null;
totop.onclick = function () {
  if (timerId) {
    clearInterval(timerId);
    timerId = null;
  }

  timerId = setInterval(function () {
    // 步进 每次移动的距离
    var step = 10;
    // 目标位置
    var target = 0;

    // 获取当前位置
    var current = getScroll().scrollTop;

    if (current > target) {
      step = -Math.abs(step);
    }

    // 判断当前是否到达目标位置
    if (Math.abs(current - target) <= Math.abs(step)) {
      clearInterval(timerId);
      document.body.scrollTop = target;
      document.documentElement.scrollTop = target;
      return;
    }

    current += step;
    document.body.scrollTop = current;
    document.documentElement.scrollTop = current;
  }, 5);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值