js常用基础案例整理(持续更新)

041-滚动视差效果

在这里插入图片描述

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    header {
      width: 100%;
      height: 200px;
      background: pink;
    }

    .a {
      visibility: hidden;
      z-index: -100;
      position: fixed;
      top: 0px;
      left: 0px;
      overflow: hidden;
      height: 280px;
      width: 100%;
    }

    .b {
      position: absolute;
      height: 460px;
      width: 100%;
      max-width: none;
    }

    span {
      display: block;
      height: 280px;
      width: 100%;
    }

    footer {
      height: 1000px;
      background-color: rgb(56, 205, 216);
    }
  </style>
</head>

<body>
  <header>
    头部
  </header>
  <section>
    <span id="d">
      哈哈哈哈哈哈哈哈哈哈
      <div class="a">
        <img class="b" src="./banner-guandian.png">
      </div>
    </span>
  </section>
  <footer>
    底部
  </footer>
</body>
<script>
  window.onload = function () {
    let A = document.querySelector('.a') //   图片外div a
    let B = document.querySelector('.b') //图片 b
    let client = document.documentElement.clientHeight //页面可视高度
    let dTop = document.getElementById('d').getBoundingClientRect().top //span元素到视窗上的距离

    // 元素出现在视口中了
    if (dTop < client) {
      // 图片设置为可见,修改transform值
      A.style.visibility = 'visible'
      A.style.transform = `translate3d(0px, ${client-(client - dTop)}px, 0px)`
      B.style.transform = `translate3d(0px,${(-(client * 0.82))+((client - dTop)*0.8)}px, 0px)`
    } else {
      A.style.transform = `translate3d(0px, ${client-10}px, 0px)`
      B.style.transform = `translate3d(0px,-${(client-10) * 0.82}px, 0px)`
    }

    // 滚动条事件
    window.onscroll = function () {
      let client = document.documentElement.clientHeight
      let dTop = document.getElementById('d').getBoundingClientRect().top
      // 元素出现在视口中了
      if (dTop < client) {
        // 同上,图片设置为可见,修改transform值
        A.style.visibility = 'visible'
        A.style.transform = `translate3d(0px, ${client-(client - dTop)}px, 0px)`
        B.style.transform = `translate3d(0px,${(-(client * 0.82))+((client - dTop)*0.8)}px, 0px)`
      }
    }
  }
</script>

</html>

040-滑动菜单指示器

在这里插入图片描述

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

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      display: flex;
      align-items: center;
      justify-content: center;
      min-height: 100vh;
      background-color: #090a20;
    }

    nav {
      position: relative;
      display: flex;
    }

    nav a {
      position: relative;
      margin: 0 20px;
      font-size: 2em;
      color: #fff;
      text-decoration: none;
    }

    nav #marker {
      position: absolute;
      height: 4px;
      width: 10%;
      background-color: #e35188;
      left: 20px;
      bottom: -8px;
      transition: .5s;
      border-radius: 4px;
    }
  </style>
</head>

<body>
  <nav>
    <div id="marker"></div>
    <a href="#">Home</a>
    <a href="#">About</a>
    <a href="#">Services</a>
    <a href="#">Portfolio</a>
    <a href="#">Team</a>
    <a href="#">Contact</a>
  </nav>
  <script>
    let marker = document.querySelector('#marker')
    let item = document.querySelectorAll('nav a')
    console.log(marker, 'marker');

    function indicator(e) {
      marker.style.left = e.offsetLeft + 'px'
      marker.style.width = e.offsetWidth + 'px'
    }

    item.forEach(link => {
      link.addEventListener('click', e => {
        indicator(e.target)
      })
    })
  </script>
</body>

</html>

039-移动端拖拽

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  div {
    width: 100px;
    height: 100px;
    background: #c33;
    position: absolute;
    left: 0;
    top: 0;
  }
</style>
<body>
  <div></div>
  <script>
    // 1.触摸元素 touchstart:  获取手指初始坐标,同时获得盒子原来的位置
    // 2.移动手指 touchmove:  计算手指的滑动距离,并且移动盒子
    // 3.离开手指 touchend
    let div = document.querySelector('div');
    let startX = 0 //获取手指初始坐标
    let startY = 0
    let x = 0 //获取盒子原来的位置
    let 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){
      // 计算手指的移动距离,手指移动之后的坐标减去手指初始的坐标
      let moveX = e.targetTouches[0].pageX - startX;
      let moveY = e.targetTouches[0].pageY - startY;
      // 移动我们的盒子   盒子原来的位置 + 手指移动的距离
      this.style.left = x + moveX + 'px'
      this.style.top = y + moveY + 'px'
      e.preventDefault();   //阻止屏幕滚动的默认行为
    })
  </script>
</body>
</html>

038-js实现轮播图渐隐渐现效果

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  .wrap {
    width: 800px;
    height: 400px;
    position: relative;
  }
.list {
  width: 800px;
  height: 400px;
  list-style: none;
  position: relative;
  padding-left: 0px;
}
.item {
  width: 100%;
  height: 100%;
  color:#fff;
  font-size: 50px;
  position: absolute;
  opacity: 0;
  transition: all .5s;
}
.btn {
  width: 50px;
  height: 100px;
  position: absolute;
  top: 150px;
  z-index: 100;
}
#goPre {
left: 0;
}
#goNext {
  right: 0;
}
.item.active {
  z-index: 10;
  opacity: 1;
}
.item:nth-child(1){
  background-color: black;
}
.item:nth-child(2){
  background-color: red;
}
.item:nth-child(3){
  background-color: yellow;
}
.item:nth-child(4){
  background-color: green;
}
.item:nth-child(5){
  background-color: pink;
}

/* 小圆点 */
.pointList {
  padding-left: 0px;
  list-style: none;
  position:absolute;
  right: 20px;
  bottom: 20px;
  z-index: 1000;
  border: 2px solid rgba(255, 255, 255, .6);
}
.point {
  width: 8px;
  height: 8px;
  background-color: rgba(0,0,0,.4);
  border-radius: 100%;
  float: left;
  margin-right: 14px;
  cursor: pointer;
}
.point.active {
  background-color: rgba(255,255,255,1);
}
</style>
<body>
  <div class="wrap">
    <ul class="list">
      <li class="item active">0</li>
      <li class="item">1</li>
      <li class="item">2</li>
      <li class="item">3</li>
      <li class="item">4</li>
    </ul>
    <ul class="pointList">
      <li class="point active" data-index='0'></li>
      <li class="point"  data-index='1'></li>
      <li class="point"  data-index='2'></li>
      <li class="point"  data-index='3'></li>
      <li class="point"  data-index='4'></li>
    </ul>
    <button type="button" class="btn" id="goPre"><</button>
    <button type="button" class="btn" id="goNext">></button>
  </div>
  <script>
    let items = document.querySelectorAll('.item') //图片
    let points = document.querySelectorAll('.point') //小圆点
    let goPreBtn = document.getElementById('goPre')
    let goNextBtn = document.getElementById('goNext')

    let index = 0 ;//表示第几张图片在展示  第index张图片有active这个类名

    let clearActive = function(){
      for(let i = 0; i < items.length; i++){
        items[i].className = 'item'
      }
      for(let i = 0; i < points.length; i++){
        points  [i].className = 'point'
      }
    }

    let goIndex = function(){
      clearActive()
      items[index].className = 'item active'
      points[index].className = 'point active'
    }

    let goNext = function(){
      if(index < 4){
        index++
      }else {
        index =0
      }
      goIndex()
    }

    let goPre = function(){
      if(index == 4){
        index=0
      }else {
        index --
      }
      goIndex()
    }
    goNextBtn.addEventListener('click',function(){
      goNext()
    })
    goPreBtn.addEventListener('click',function(){
      goPre()
    })

    for(let i = 0; i < points.length; i++){
      points[i].addEventListener('click',function(){
        let pointIdx = this.getAttribute('data-index')
        index = pointIdx
        goIndex()
      })
    }
// 自动轮播
let timer = setInterval(()=>{
  goNextBtn.click()
},3000)
  </script>
</body>

</html>

037-js实现图片懒加载

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  html body {
    padding: 0;
    margin: 0;
  }
  img {
      width: 400px;
      display: block;
      margin: 0 auto;
      height: 300px;
    }
  div {
    height: 400px;
    border: 1px solid red;
  }
</style>
<body>
  <img data-src="./banner.jpg" alt="">
  <img data-src="./jj.jpeg" alt="" >
  <img data-src="./pic/1.jpg" alt="" >
  <img data-src="./pic/2.jpg" alt="">
  <img data-src="./pic/3.jpg" alt="">
  <img data-src="./pic/4.jpg" alt="">
  <img data-src="./pic/5.jpg" alt="" >
  <script>
  const imgs = document.querySelectorAll('img');
  const len = imgs.length
  function isShow(img) {
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    const windowHeight = document.documentElement.clientHeight;
    const offsetTop = img.offsetTop
    //判断当前img是否出现了在视野中。
    return offsetTop < (windowHeight + scrollTop)
  }
  // 节流函数
  function throttle(fn, delay) {
    // oldTime为上一次触发回调的时间, timer是定时器
    let oldTime = 0, timer = null;
    // 将throttle处理结果当作函数返回
    return function () {
      // 记录本次触发回调的时间
      let nowTime = +new Date()
      // 判断上次触发的时间和本次触发的时间差是否小于时间间隔的阈值
      if (nowTime - oldTime < delay) {
        // 如果时间间隔小于我们设定的时间间隔阈值,则为本次触发操作设立一个新的定时器
        clearTimeout(timer)
        timer = setTimeout(function () {
          oldTime = nowTime
          fn()
        }, delay)
      } else {
        // 如果时间间隔超出了我们设定的时间间隔阈值,那就不等了,无论如何要反馈给用户一次响应
        oldTime = nowTime
        fn()
      }
    }
  }
  function lazyLoad() {
    let count = 0;
    //利用闭包来保存一个变量,每次记录更换src的最终位置,这样就不用每次都全部遍历
    return () => {
      for (var i = count; i < len; i++) {
        //如果img到达视野内
        if (isShow(imgs[i])) {
          imgs[i].src = imgs[i].getAttribute('data-src');
          //把img的src换成data-src里面的真实地址,并且记录下最后换到那个位置,
          count = i;
        }
      }
    }
  }
  //用变量来接收lazyLoad运行结果
  let lazy = lazyLoad()
  //首页加载刚进去需要加载一下
  lazy()
  window.addEventListener('scroll', throttle(lazy, 300), false)

  </script>
</body>

</html>

在这里插入图片描述

036-网页日历

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    #data {
      width: 300px;
      border: 1px solid #000;
      margin: 20px auto;
    }
    #data > p {
      display: flex;
    }
    #data > p span{
      padding: 0 10px;
    }
    #data > h5 {
      text-align: center;
    }
    #prev,#next {
      cursor: pointer;
    }
    #nian {
      flex: 1;
      text-align: center;
    }
    #title {
      overflow: hidden;
      list-style: none;
      background-color: #ccc;
    }
    #title li {
      float: left;
      width: 40px;
      height: 26px;
      line-height: 26px;
      text-align: center;
    }
    #date {
      overflow: hidden;
      list-style: none;
    }
    #date li {
      float: left;
      width: 34px;
      height: 34px;
      margin: 1px 1px;
      border: 2px solid #000;
      line-height: 34px;
      text-align: center;
      cursor: pointer;
      list-style: none;
    }
    #date > .hover:hover {
      border:2px solid red;
    }
    .active{
      color:red
    }
  </style>
</head>
<body>
  <div id="data">
    <p>
      <span id="prev">上一月</span>
      <span id="nian">2022</span>
      <span id="next">下一月</span>
    </p>
    <h5 id="yue">一月</h5>
    <ul id="title">
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
    </ul>
    <ul id="date"></ul>
  </div>

  <script>
    let date = new Date(); //获取默认时间对象
    add() // 当页面第一次进入时触发一下

    function add() {
      let cYear = date.getFullYear(); //获取当前年份
      let cMonth = date.getMonth(); //获取当前月份
      let cDay = date.getDate() // 当前的天
      console.log(cDay,'1');

      // 每个月的第一天是周几
      let week = new Date(cYear,cMonth,1).getDay()
      // 获取每个月的天数
      let days = new Date(cYear,cMonth+1,-1).getDate()+1;

      let arr = ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月',]

      document.getElementById('nian').innerHTML = cYear
      document.getElementById('yue').innerHTML = arr[cMonth]

      let html = '';

      for(var i = 0; i < week; i++) {
        html += '<li></li>'
      }

      for(var i = 1; i <= days; i++) {
        if( i == cDay) {
          html += '<li class="active">'+i+'</li>'
        }
        html += '<li class="hover">'+i+'</li>'
      }
      document.getElementById('date').innerHTML = html

    }

    document.getElementById('prev').onclick = function(){
      date.setMonth(date.getMonth()-1);
      add()
    }
    document.getElementById('next').onclick = function(){
      date.setMonth(date.getMonth()+1);
      add()
    }
  </script>
</body>
</html>

035-记住用户名(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>
  </head>

  <body>
    <input type="text" id="username" />
    <input type="checkbox" name="" 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
      }
      remember.addEventListener('change', function () {
        if (this.checked) {
          localStorage.setItem('username', username.value)
        } else {
          localStorage.removeItem('username')
        }
      })
    </script>
  </body>
</html>

034-js基础轮播图(左右滑动轮播)

效果图:

示例代码:

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

033-京东放大镜效果(js代码)

效果图:


示例代码:

window.addEventListener('load', function () {
  var preview_img = document.querySelector('.preview_img')
  var mask = document.querySelector('.mask')
  var big = document.querySelector('.big')
  // 1. 当我们鼠标经过 preview_img 就显示和隐藏 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) {
    // (1). 先计算出鼠标在盒子内的坐标
    var x = e.pageX - this.offsetLeft
    var y = e.pageY - this.offsetTop
    // console.log(x, y);
    // (2) 减去盒子高度 300的一半 是 150 就是我们mask 的最终 left 和top值了
    // (3) 我们mask 移动的距离
    var maskX = x - mask.offsetWidth / 2
    var maskY = y - mask.offsetHeight / 2
    // (4) 如果x 坐标小于了0 就让他停在0 的位置
    // 遮挡层的最大移动距离
    var maskMax = preview_img.offsetWidth - mask.offsetWidth
    if (maskX <= 0) {
      maskX = 0
    } else if (maskX >= maskMax) {
      maskX = maskMax
    }
    if (maskY <= 0) {
      maskY = 0
    } else if (maskY >= maskMax) {
      maskY = maskMax
    }
    mask.style.left = maskX + 'px'
    mask.style.top = maskY + 'px'
    // 3. 大图片的移动距离 = 遮挡层移动距离 * 大图片最大移动距离 / 遮挡层的最大移动距离
    // 大图
    var bigIMg = document.querySelector('.bigImg')
    // 大图片最大移动距离
    var bigMax = bigIMg.offsetWidth - big.offsetWidth
    // 大图片的移动距离 X Y
    var bigX = (maskX * bigMax) / maskMax
    var bigY = (maskY * bigMax) / maskMax
    bigIMg.style.left = -bigX + 'px'
    bigIMg.style.top = -bigY + 'px'
  })
})

032-简单动画函数封装

效果图:

示例代码:

<!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 {
        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>

031-仿淘宝固定侧边栏+返回顶部按钮

效果图:


示例代码:

<!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'
        }
      })
      // 3. 当我们点击了返回顶部模块,就让窗口滚动的页面的最上方
      goBack.addEventListener('click', function () {
        // 里面的x和y 不跟单位的 直接写数字即可
        // window.scroll(0, 0);
        // 因为是窗口滚动 所以对象是window
        animate(window, 0)
      })
      // 动画函数
      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 - window.pageYOffset) / 10
          step = step > 0 ? Math.ceil(step) : Math.floor(step)
          if (window.pageYOffset == target) {
            // 停止动画 本质是停止定时器
            clearInterval(obj.timer)
            // 回调函数写到定时器结束里面
            // if (callback) {
            //     // 调用函数
            //     callback();
            // }
            callback && callback()
          }
          // 把每次加1 这个步长值改为一个慢慢变小的值  步长公式:(目标值 - 现在的位置) / 10
          // obj.style.left = window.pageYOffset + step + 'px';
          window.scroll(0, window.pageYOffset + step)
        }, 15)
      }
    </script>
  </body>
</html>

030-拖动的模态框

效果图:



示例代码:

<!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, 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>

029-发送短信倒计时案例

效果图:


示例代码:

<!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="number"> <button>发送</button>
    <script>
        // 按钮点击之后,会禁用 disabled 为true 
        // 同时按钮里面的内容会变化, 注意 button 里面的内容通过 innerHTML修改
        // 里面秒数是有变化的,因此需要用到定时器
        // 定义一个变量,在定时器里面,不断递减
        // 如果变量为0 说明到了时间,我们需要停止定时器,并且复原按钮初始状态
        var btn = document.querySelector('button');
        var time = 3; // 定义剩下的秒数
        btn.addEventListener('click', function() {
            btn.disabled = true;
            var timer = setInterval(function() {
                if (time == 0) {
                    // 清除定时器和复原按钮
                    clearInterval(timer);
                    btn.disabled = false;
                    btn.innerHTML = '发送';
                } else {
                    btn.innerHTML = '还剩下' + time + '秒';
                    time--;
                }
            }, 1000);

        })
    </script>
</body>

</html>

028-倒计时效果

效果图:

示例代码:

<!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>
        // 1. 获取元素 
        var hour = document.querySelector('.hour'); // 小时的黑色盒子
        var minute = document.querySelector('.minute'); // 分钟的黑色盒子
        var second = document.querySelector('.second'); // 秒数的黑色盒子
        var inputTime = +new Date('2050-8-8 18:00:00'); // 返回的是用户输入时间总的毫秒数
        countDown(); // 我们先调用一次这个函数,防止第一次刷新页面有空白 
        // 2. 开启定时器
        setInterval(countDown, 1000);

        function countDown() {
            var nowTime = +new Date(); // 返回的是当前时间总的毫秒数
            var times = (inputTime - nowTime) / 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

027-模拟京东快递单号查询案例

效果图:


示例代码:

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

      .search {
        position: relative;
        width: 178px;
        margin: 100px;
      }

      .con {
        display: none;
        position: absolute;
        top: -40px;
        width: 171px;
        border: 1px solid rgba(0, 0, 0, 0.2);
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        padding: 5px 0;
        font-size: 18px;
        line-height: 20px;
        color: #333;
      }

      .con::before {
        content: '';
        width: 0;
        height: 0;
        position: absolute;
        top: 28px;
        left: 18px;
        border: 8px solid #000;
        border-style: solid dashed dashed;
        border-color: #fff transparent transparent;
      }
    </style>
  </head>

  <body>
    <div class="search">
      <div class="con">123</div>
      <input type="text" placeholder="请输入您的快递单号" class="jd" />
    </div>
    <script>
      // 快递单号输入内容时, 上面的大号字体盒子(con)显示(这里面的字号更大)
      // 表单检测用户输入: 给表单添加键盘事件
      // 同时把快递单号里面的值(value)获取过来赋值给 con盒子(innerText)做为内容
      // 如果快递单号里面内容为空,则隐藏大号字体盒子(con)盒子
      var con = document.querySelector('.con')
      var jd_input = document.querySelector('.jd')
      jd_input.addEventListener('keyup', function () {
        // console.log('输入内容啦');
        if (this.value == '') {
          con.style.display = 'none'
        } else {
          con.style.display = 'block'
          con.innerText = this.value
        }
      })
      // 当我们失去焦点,就隐藏这个con盒子
      jd_input.addEventListener('blur', function () {
        con.style.display = 'none'
      })
      // 当我们获得焦点,就显示这个con盒子
      jd_input.addEventListener('focus', function () {
        if (this.value !== '') {
          con.style.display = 'block'
        }
      })
    </script>
  </body>
</html>

026-模拟京东按键输入内容

效果图:

示例代码:

<!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" />
    <script>
      // 核心思路: 检测用户是否按下了s 键,如果按下s 键,就把光标定位到搜索框里面
      // 使用键盘事件对象里面的keyCode 判断用户按下的是否是s键
      // 搜索框获得焦点: 使用 js 里面的 focus() 方法
      var search = document.querySelector('input')
      document.addEventListener('keyup', function (e) {
        // console.log(e.keyCode);
        if (e.keyCode === 83) {
          search.focus()
        }
      })
    </script>
  </body>
</html>

025-跟随鼠标移动的小人

效果图:

示例代码:

<!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>
        img {
            position: absolute;
            top: 2px;
        }
    </style>
</head>

<body>
    <img src="images/angel.gif" alt="">
    <script>
        var pic = document.querySelector('img');
        document.addEventListener('mousemove', function(e) {
            // 1. mousemove只要我们鼠标移动 就会触发这个事件
            // 2.核心原理: 每次鼠标移动,我们都会获得最新的鼠标坐标, 把这个x和y坐标做为图片的top和left 值就可以移动图片
            var x = e.pageX;
            var y = e.pageY;
            console.log('x坐标是' + x, 'y坐标是' + y);
            //3 . 千万不要忘记给left 和top 添加px 单位
            pic.style.left = x - 50 + 'px';
            pic.style.top = y - 40 + 'px';

        });
    </script>
</body>

</html>

024-动态生成表格案例

效果图:

示例代码:

<!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>
      table {
        width: 500px;
        margin: 100px auto;
        border-collapse: collapse;
        text-align: center;
      }

      td,
      th {
        border: 1px solid #333;
      }

      thead tr {
        height: 40px;
        background-color: #ccc;
      }
    </style>
  </head>

  <body>
    <table cellspacing="0">
      <thead>
        <tr>
          <th>姓名</th>
          <th>科目</th>
          <th>成绩</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    <script>
      // 1.数据
      var datas = [
        {
          name: 'test0',
          subject: 'JavaScript',
          score: 10,
        },
        {
          name: 'test1',
          subject: 'JavaScript',
          score: 9,
        },
        {
          name: 'test2',
          subject: 'JavaScript',
          score: 9,
        },
        {
          name: 'test3',
          subject: 'JavaScript',
          score: 8,
        },
        {
          name: 'test4',
          subject: 'JavaScript',
          score: 1,
        },
      ]
      // 2. 往tbody 里面创建行: 有几个人(通过数组的长度)我们就创建几行
      var tbody = document.querySelector('tbody')
      for (var i = 0; i < datas.length; i++) {
        // 外面的for循环管行 tr
        // 1. 创建 tr行
        var tr = document.createElement('tr')
        tbody.appendChild(tr)
        // 2. 行里面创建单元格(跟数据有关系的3个单元格) td 单元格的数量取决于每个对象里面的属性个数  for循环遍历对象 datas[i]
        for (var k in datas[i]) {
          // 里面的for循环管列 td
          // 创建单元格
          var td = document.createElement('td')
          // 把对象里面的属性值 datas[i][k] 给 td
          // console.log(datas[i][k]);
          td.innerHTML = datas[i][k]
          tr.appendChild(td)
        }
        // 3. 创建有删除2个字的单元格
        var td = document.createElement('td')
        td.innerHTML = '<a href="javascript:;">删除 </a>'
        tr.appendChild(td)
      }
      // 4. 删除操作 开始
      var as = document.querySelectorAll('a')
      for (var i = 0; i < as.length; i++) {
        as[i].onclick = function () {
          // 点击a 删除 当前a 所在的行(链接的爸爸的爸爸)  node.removeChild(child)
          tbody.removeChild(this.parentNode.parentNode)
        }
      }
      // for(var k in obj) {
      //     k 得到的是属性名
      //     obj[k] 得到是属性值
      // }
    </script>
  </body>
</html>

023-删除留言案例

效果图:
在这里插入图片描述
示例代码:

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

      body {
        padding: 100px;
      }
      textarea {
        width: 200px;
        height: 100px;
        border: 1px solid pink;
        outline: none;
        resize: none;
      }
      ul {
        margin-top: 50px;
      }
      li {
        width: 300px;
        padding: 5px;
        background-color: rgb(245, 209, 243);
        color: red;
        font-size: 14px;
        margin: 15px 0;
      }
      li a {
        float: right;
      }
    </style>
  </head>

  <body>
    <textarea name="" id=""></textarea>
    <button>发布</button>
    <ul></ul>
    <script>
      // 1. 获取元素
      var btn = document.querySelector('button')
      var text = document.querySelector('textarea')
      var ul = document.querySelector('ul')
      // 2. 注册事件
      btn.onclick = function () {
        if (text.value == '') {
          alert('您没有输入内容')
          return false
        } else {
          // (1) 创建元素
          var li = document.createElement('li')
          // 先有li 才能赋值
          li.innerHTML = text.value + "<a href='javascript:;'>删除</a>"
          // (2) 添加元素
          // ul.appendChild(li);
          ul.insertBefore(li, ul.children[0])
          // (3) 删除元素 删除的是当前链接的li  它的父亲
          var del = document.querySelectorAll('a')
          for (var i = 0; i < del.length; i++) {
            del[i].onclick = function () {
              // node.removeChild(child); 删除的是 li 当前a所在的li  this.parentNode;
              ul.removeChild(this.parentNode)
            }
          }
        }
      }
    </script>
  </body>
</html>

022-新浪下拉菜单

效果图

示例代码:

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

      li {
        list-style-type: none;
      }

      a {
        text-decoration: none;
        font-size: 14px;
      }

      .nav {
        margin: 100px;
      }

      .nav > li {
        position: relative;
        float: left;
        width: 80px;
        height: 41px;
        text-align: center;
      }

      .nav li a {
        display: block;
        width: 100%;
        height: 100%;
        line-height: 41px;
        color: #333;
      }

      .nav > li > a:hover {
        background-color: #eee;
      }

      .nav ul {
        display: none;
        position: absolute;
        top: 41px;
        left: 0;
        width: 100%;
        border-left: 1px solid #fecc5b;
        border-right: 1px solid #fecc5b;
      }

      .nav ul li {
        border-bottom: 1px solid #fecc5b;
      }

      .nav ul li a:hover {
        background-color: #fff5da;
      }
    </style>
  </head>

  <body>
    <ul class="nav">
      <li>
        <a href="#">微博</a>
        <ul>
          <li>
            <a href="">私信</a>
          </li>
          <li>
            <a href="">评论</a>
          </li>
          <li>
            <a href="">@我</a>
          </li>
        </ul>
      </li>
      <li>
        <a href="#">微博</a>
        <ul>
          <li>
            <a href="">私信</a>
          </li>
          <li>
            <a href="">评论</a>
          </li>
          <li>
            <a href="">@我</a>
          </li>
        </ul>
      </li>
      <li>
        <a href="#">微博</a>
        <ul>
          <li>
            <a href="">私信</a>
          </li>
          <li>
            <a href="">评论</a>
          </li>
          <li>
            <a href="">@我</a>
          </li>
        </ul>
      </li>
      <li>
        <a href="#">微博</a>
        <ul>
          <li>
            <a href="">私信</a>
          </li>
          <li>
            <a href="">评论</a>
          </li>
          <li>
            <a href="">@我</a>
          </li>
        </ul>
      </li>
    </ul>
    <script>
      // 1. 获取元素
      var nav = document.querySelector('.nav')
      var lis = nav.children // 得到4个小li
      // 2.循环注册事件
      for (var i = 0; i < lis.length; i++) {
        lis[i].onmouseover = function () {
          this.children[1].style.display = 'block'
        }
        lis[i].onmouseout = function () {
          this.children[1].style.display = 'none'
        }
      }
    </script>
  </body>
</html>

021-Tab栏切换(仿京东)

效果图

示例代码:

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

      li {
        list-style-type: none;
      }

      .tab {
        width: 978px;
        margin: 100px auto;
      }

      .tab_list {
        height: 39px;
        border: 1px solid #ccc;
        background-color: #f1f1f1;
      }

      .tab_list li {
        float: left;
        height: 39px;
        line-height: 39px;
        padding: 0 20px;
        text-align: center;
        cursor: pointer;
      }

      .tab_list .current {
        background-color: #c81623;
        color: #fff;
      }

      .item_info {
        padding: 20px 0 0 20px;
      }

      .item {
        display: none;
      }
    </style>
  </head>

  <body>
    <div class="tab">
      <div class="tab_list">
        <ul>
          <li class="current">商品介绍</li>
          <li>规格与包装</li>
          <li>售后保障</li>
          <li>商品评价(50000)</li>
          <li>手机社区</li>
        </ul>
      </div>
      <div class="tab_con">
        <div class="item" style="display: block;">
          商品介绍模块内容
        </div>
        <div class="item">
          规格与包装模块内容
        </div>
        <div class="item">
          售后保障模块内容
        </div>
        <div class="item">
          商品评价(50000)模块内容
        </div>
        <div class="item">
          手机社区模块内容
        </div>
      </div>
    </div>
    <script>
      // 获取元素
      var tab_list = document.querySelector('.tab_list')
      var lis = tab_list.querySelectorAll('li')
      var items = document.querySelectorAll('.item')
      // for循环绑定点击事件
      for (var i = 0; i < lis.length; i++) {
        // 开始给5个小li 设置索引号
        lis[i].setAttribute('index', i)
        lis[i].onclick = function () {
          // 1. 上的模块选项卡,点击某一个,当前这一个底色会是红色,其余不变(排他思想) 修改类名的方式

          // 干掉所有人 其余的li清除 class 这个类
          for (var i = 0; i < lis.length; i++) {
            lis[i].className = ''
          }
          // 留下我自己
          this.className = 'current'
          // 2. 下面的显示内容模块
          var index = this.getAttribute('index')
          console.log(index)
          // 干掉所有人 让其余的item 这些div 隐藏
          for (var i = 0; i < items.length; i++) {
            items[i].style.display = 'none'
          }
          // 留下我自己 让对应的item 显示出来
          items[index].style.display = 'block'
        }
      }
    </script>
  </body>
</html>


020-全选与反选

效果图

示例代码:

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

      .wrap {
        width: 300px;
        margin: 100px auto 0;
      }

      table {
        border-collapse: collapse;
        border-spacing: 0;
        border: 1px solid #c0c0c0;
        width: 300px;
      }

      th,
      td {
        border: 1px solid #d0d0d0;
        color: #404060;
        padding: 10px;
      }

      th {
        background-color: #09c;
        font: bold 16px '微软雅黑';
        color: #fff;
      }

      td {
        font: 14px '微软雅黑';
      }

      tbody tr {
        background-color: #f0f0f0;
      }

      tbody tr:hover {
        cursor: pointer;
        background-color: #fafafa;
      }
    </style>
  </head>

  <body>
    <div class="wrap">
      <table>
        <thead>
          <tr>
            <th>
              <input type="checkbox" id="j_cbAll" />
            </th>
            <th>商品</th>
            <th>价钱</th>
          </tr>
        </thead>
        <tbody id="j_tb">
          <tr>
            <td>
              <input type="checkbox" />
            </td>
            <td>iPhone8</td>
            <td>8000</td>
          </tr>
          <tr>
            <td>
              <input type="checkbox" />
            </td>
            <td>iPad Pro</td>
            <td>5000</td>
          </tr>
          <tr>
            <td>
              <input type="checkbox" />
            </td>
            <td>iPad Air</td>
            <td>2000</td>
          </tr>
          <tr>
            <td>
              <input type="checkbox" />
            </td>
            <td>Apple Watch</td>
            <td>2000</td>
          </tr>
        </tbody>
      </table>
    </div>
    <script>
      // 1. 全选和取消全选做法:  让下面所有复选框的checked属性(选中状态) 跟随 全选按钮即可
      // 获取元素
      var j_cbAll = document.getElementById('j_cbAll') // 全选按钮
      var j_tbs = document.getElementById('j_tb').getElementsByTagName('input') // 下面所有的复选框
      // 注册事件
      j_cbAll.onclick = function () {
        // this.checked 它可以得到当前复选框的选中状态如果是true 就是选中,如果是false 就是未选中
        console.log(this.checked)
        for (var i = 0; i < j_tbs.length; i++) {
          j_tbs[i].checked = this.checked
        }
      }
      // 2. 下面复选框需要全部选中, 上面全选才能选中做法: 给下面所有复选框绑定点击事件,每次点击,都要循环查看下面所有的复选框是否有没选中的,如果有一个没选中的, 上面全选就不选中。
      for (var i = 0; i < j_tbs.length; i++) {
        j_tbs[i].onclick = function () {
          // flag 控制全选按钮是否选中
          var flag = true
          // 每次点击下面的复选框都要循环检查者4个小按钮是否全被选中
          for (var i = 0; i < j_tbs.length; i++) {
            if (!j_tbs[i].checked) {
              flag = false
              break // 退出for循环 这样可以提高执行效率 因为只要有一个没有选中,剩下的就无需循环判断了
            }
          }
          j_cbAll.checked = flag
        }
      }
    </script>
  </body>
</html>

019-表格隔行变色

效果图

示例代码:

<!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>
      table {
        width: 800px;
        margin: 100px auto;
        text-align: center;
        border-collapse: collapse;
        font-size: 14px;
      }

      thead tr {
        height: 30px;
        background-color: skyblue;
      }

      tbody tr {
        height: 30px;
      }

      tbody td {
        border-bottom: 1px solid #d7d7d7;
        font-size: 12px;
        color: blue;
      }

      .bg {
        background-color: pink;
      }
    </style>
  </head>

  <body>
    <table>
      <thead>
        <tr>
          <th>代码</th>
          <th>名称</th>
          <th>最新公布净值</th>
          <th>累计净值</th>
          <th>前单位净值</th>
          <th>净值增长率</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>003526</td>
          <td>农银金穗3个月定期开放债券</td>
          <td>1.075</td>
          <td>1.079</td>
          <td>1.074</td>
          <td>+0.047%</td>
        </tr>
        <tr>
          <td>003526</td>
          <td>农银金穗3个月定期开放债券</td>
          <td>1.075</td>
          <td>1.079</td>
          <td>1.074</td>
          <td>+0.047%</td>
        </tr>
        <tr>
          <td>003526</td>
          <td>农银金穗3个月定期开放债券</td>
          <td>1.075</td>
          <td>1.079</td>
          <td>1.074</td>
          <td>+0.047%</td>
        </tr>
        <tr>
          <td>003526</td>
          <td>农银金穗3个月定期开放债券</td>
          <td>1.075</td>
          <td>1.079</td>
          <td>1.074</td>
          <td>+0.047%</td>
        </tr>
        <tr>
          <td>003526</td>
          <td>农银金穗3个月定期开放债券</td>
          <td>1.075</td>
          <td>1.079</td>
          <td>1.074</td>
          <td>+0.047%</td>
        </tr>
        <tr>
          <td>003526</td>
          <td>农银金穗3个月定期开放债券</td>
          <td>1.075</td>
          <td>1.079</td>
          <td>1.074</td>
          <td>+0.047%</td>
        </tr>
      </tbody>
    </table>
    <script>
      // 1.获取元素 获取的是 tbody 里面所有的行
      var trs = document.querySelector('tbody').querySelectorAll('tr')
      // 2. 利用循环绑定注册事件
      for (var i = 0; i < trs.length; i++) {
        // 3. 鼠标经过事件 onmouseover
        trs[i].onmouseover = function () {
          // console.log(11);
          this.className = 'bg'
        }
        // 4. 鼠标离开事件 onmouseout
        trs[i].onmouseout = function () {
          this.className = ''
        }
      }
    </script>
  </body>
</html>

018-开关灯效果

效果图

示例代码:

<!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 id="btn">开关灯</button>
    <script>
      var btn = document.getElementById('btn')
      var flag = 0
      btn.onclick = function () {
        if (flag == 0) {
          document.body.style.backgroundColor = 'black'
          flag = 1
        } else {
          document.body.style.backgroundColor = '#fff'
          flag = 0
        }
      }
    </script>
  </body>
</html>

017-仿新浪注册页面框

效果图


示例代码:

<!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: 600px;
        margin: 100px auto;
      }

      .message {
        display: inline-block;
        font-size: 12px;
        color: #999;
        background: url(images/mess.png) no-repeat left center;
        padding-left: 20px;
      }

      .wrong {
        color: red;
        background-image: url(images/wrong.png);
      }

      .right {
        color: green;
        background-image: url(images/right.png);
      }
    </style>
  </head>

  <body>
    <div class="register">
      <input type="password" class="ipt" />
      <p class="message">请输入6~16位密码</p>
    </div>
    <script>
      // 首先判断的事件是表单失去焦点 onblur
      // 如果输入正确则提示正确的信息颜色为绿色小图标变化
      // 如果输入不是6到16位,则提示错误信息颜色为红色 小图标变化
      // 因为里面变化样式较多,我们采取className修改样式
      // 1.获取元素
      var ipt = document.querySelector('.ipt')
      var message = document.querySelector('.message')
      //2. 注册事件 失去焦点
      ipt.onblur = function () {
        // 根据表单里面值的长度 ipt.value.length
        if (this.value.length < 6 || this.value.length > 16) {
          // console.log('错误');
          message.className = 'message wrong'
          message.innerHTML = '您输入的位数不对要求6~16位'
        } else {
          message.className = 'message right'
          message.innerHTML = '您输入的正确'
        }
      }
    </script>
  </body>
</html>

016-淘宝关闭二维码案例

效果图


示例代码:

<!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 {
        position: relative;
        width: 74px;
        height: 88px;
        border: 1px solid #ccc;
        margin: 100px auto;
        font-size: 12px;
        text-align: center;
        color: #f40;
        /* display: block; */
      }
      .box img {
        width: 60px;
        margin-top: 5px;
      }
      .close-btn {
        position: absolute;
        top: -1px;
        left: -16px;
        width: 14px;
        height: 14px;
        border: 1px solid #ccc;
        line-height: 14px;
        font-family: Arial, Helvetica, sans-serif;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div class="box">
      淘宝二维码
      <img src="images/tao.png" alt="" />
      <i class="close-btn">×</i>
    </div>
    <script>
      // 1. 获取元素
      var btn = document.querySelector('.close-btn')
      var box = document.querySelector('.box')
      // 2.注册事件 程序处理
      btn.onclick = function () {
        box.style.display = 'none'
      }
    </script>
  </body>
</html>

015-仿京东显示隐藏密码效果

效果图


示例代码:

<!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 {
        position: relative;
        width: 400px;
        border-bottom: 1px solid #ccc;
        margin: 100px auto;
      }

      .box input {
        width: 370px;
        height: 30px;
        border: 0;
        outline: none;
      }

      .box img {
        position: absolute;
        top: 2px;
        right: 2px;
        width: 24px;
      }
    </style>
  </head>

  <body>
    <div class="box">
      <label for="">
        <img src="images/close.png" alt="" id="eye" />
      </label>
      <input type="password" name="" id="pwd" />
    </div>
    <script>
      // 1. 获取元素
      var eye = document.getElementById('eye')
      var pwd = document.getElementById('pwd')
      // 2. 注册事件 处理程序
      var flag = 0
      eye.onclick = function () {
        // 点击一次之后, flag 一定要变化
        if (flag == 0) {
          pwd.type = 'text'
          eye.src = 'images/open.png'
          flag = 1 // 赋值操作
        } else {
          pwd.type = 'password'
          eye.src = 'images/close.png'
          flag = 0
        }
      }
    </script>
  </body>
</html>

014-查找字符串"abcoefoxyozzopp"中所有o出现的位置以及次数

示例代码:

// 核心算法:先查找第一个o出现的位置
        // 然后 只要indexOf 返回的结果不是 -1 就继续往后查找
        // 因为indexOf 只能查找到第一个,所以后面的查找,一定是当前索引加1,从而继续查找
        var str = "oabcoefoxyozzopp";
        var index = str.indexOf('o');
        var num = 0;
        // console.log(index);
        while (index !== -1) {
            console.log(index);
            num++;
            index = str.indexOf('o', index + 1);
        }
        console.log('o出现的次数是: ' + num);
        
          //  判断一个字符串 'abcoefoxyozzopp' 中出现次数最多的字符,并统计其次数。
        // o.a = 1
        // o.b = 1
        // o.c = 1
        // o.o = 4
        // 核心算法:利用 charAt() 遍历这个字符串
        // 把每个字符都存储给对象, 如果对象没有该属性,就为1,如果存在了就 +1
        // 遍历对象,得到最大值和该字符
        var str = 'abcoefoxyozzopp';
        var o = {};
        for (var i = 0; i < str.length; i++) {
            var chars = str.charAt(i); // chars 是 字符串的每一个字符
            if (o[chars]) { // o[chars] 得到的是属性值
                o[chars]++;
            } else {
                o[chars] = 1;
            }
        }
        console.log(o);
        // 2. 遍历对象
        var max = 0;
        var ch = '';
        for (var k in o) {
            // k 得到是 属性名
            // o[k] 得到的是属性值
            if (o[k] > max) {
                max = o[k];
                ch = k;
            }
        }
        console.log(max);
        console.log('最多的字符是' + ch);

013-去除数组中重复的元素

示例代码:

// 数组去重 ['c', 'a', 'z', 'a', 'x', 'a', 'x', 'c', 'b'] 要求去除数组中重复的元素。
// 1.目标: 把旧数组里面不重复的元素选取出来放到新数组中, 重复的元素只保留一个, 放到新数组中去重。
// 2.核心算法: 我们遍历旧数组, 然后拿着旧数组元素去查询新数组, 如果该元素在新数组里面没有出现过, 我们就添加, 否则不添加。
// 3.我们怎么知道该元素没有存在? 利用 新数组.indexOf(数组元素) 如果返回时 - 1 就说明 新数组里面没有改元素
// 封装一个 去重的函数 unique 独一无二的
      function unique(arr) {
        var newArr = []
        for (var i = 0; i < arr.length; i++) {
          if (newArr.indexOf(arr[i]) === -1) {
            newArr.push(arr[i])
          }
        }
        return newArr
      }
      var demo = unique(['blue', 'green', 'blue'])
      console.log(demo)

012-静态倒计时效果

示例代码:

// 倒计时效果
// 1.核心算法:输入的时间减去现在的时间就是剩余的时间,即倒计时 ,但是不能拿着时分秒相减,比如 05 分减去25分,结果会是负数的。
// 2.用时间戳来做。用户输入时间总的毫秒数减去现在时间的总的毫秒数,得到的就是剩余时间的毫秒数。
// 3.把剩余时间总的毫秒数转换为天、时、分、秒 (时间戳转换为时分秒)
// 转换公式如下:
//  d = parseInt(总秒数/ 60/60 /24);    //  计算天数
//  h = parseInt(总秒数/ 60/60 %24)   //   计算小时
//  m = parseInt(总秒数 /60 %60 );     //   计算分数
//  s = parseInt(总秒数%60);            //   计算当前秒数
function countDown(time) {
    var nowTime = +new Date() // 返回的是当前时间总的毫秒数
    var inputTime = +new Date(time) // 返回的是用户输入时间总的毫秒数
    var times = (inputTime - nowTime) / 1000 // times是剩余时间总的秒数
    var d = parseInt(times / 60 / 60 / 24) // 天
    d = d < 10 ? '0' + d : d
    var h = parseInt((times / 60 / 60) % 24) //时
    h = h < 10 ? '0' + h : h
    var m = parseInt((times / 60) % 60) // 分
    m = m < 10 ? '0' + m : m
    var s = parseInt(times % 60) // 秒
    s = s < 10 ? '0' + s : s
    return d + '天' + h + '时' + m + '分' + s + '秒'
}
    console.log(countDown('2020-5-1 18:00:00'))
    
     // 获得Date总的毫秒数(时间戳)  不是当前时间的毫秒数 而是距离1970年1月1号过了多少毫秒数
        // 1. 通过 valueOf()  getTime()
        var date = new Date();
        console.log(date.valueOf()); // 就是 我们现在时间 距离1970.1.1 总的毫秒数
        console.log(date.getTime());
        // 2. 简单的写法 (最常用的写法)
        var date1 = +new Date(); // +new Date()  返回的就是总的毫秒数
        // 3. H5 新增的 获得总的毫秒数
        console.log(Date.now());

011-基础冒泡排序

示例代码:

  // 冒泡排序
        // var arr = [5, 4, 3, 2, 1];
        var arr = [4, 1, 2, 3, 5];
        for (var i = 0; i <= arr.length - 1; i++) { // 外层循环管趟数 
            for (var j = 0; j <= arr.length - i - 1; j++) { // 里面的循环管每一趟的交换次数
                // 内部交换2个变量的值 前一个和后面一个数组元素相比较
                if (arr[j] < arr[j + 1]) {
                    var temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }

            }
        }
        console.log(arr);

010-删除指定数组的元素

示例代码:

  // 将数组[2, 0, 6, 1, 77, 0, 52, 0, 25, 7]中的 0 去掉后,形成一个不包含 0 的新数组。
        // 1、需要一个新数组用于存放筛选之后的数据。
        // 2、遍历原来的数组, 把不是 0 的数据添加到新数组里面(此时要注意采用数组名 + 索引的格式接收数据)。
        // 3、新数组里面的个数, 用 length 不断累加。
        var arr = [2, 0, 6, 1, 77, 0, 52, 0, 25, 7];
        var newArr = [];
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] != 0) {
                newArr[newArr.length] = arr[i];
            }
        }
        console.log(newArr);

009-往数组存放100个值

示例代码:

  // 新建一个数组,里面存放10个整数( 1~10)
        // 核心原理:使用循环来追加数组。
        // 1、声明一个空数组 arr。
        // 2、循环中的计数器 i  可以作为数组元素存入。
        // 3、由于数组的索引号是从0开始的, 因此计数器从 0 开始更合适,存入的数组元素要+1。
        var arr = [];
        for (var i = 0; i < 100; i++) {
            // arr = i; 不要直接给数组名赋值 否则以前的元素都没了
            arr[i] = i + 1;
        }
        console.log(arr);

008-求数组中最大的值

示例代码:

  // 求数组[2,6,1,77,52,25,7]中的最大值
        // 声明一个保存最大元素的变量 max。
        // 默认最大值可以取数组中的第一个元素。
        // 遍历这个数组,把里面每个数组元素和 max 相比较。
        // 如果这个数组元素大于max 就把这个数组元素存到 max 里面,否则继续下一轮比较。
        // 最后输出这个 max
        var arr = [2, 6, 1, 77, 52, 25, 7, 99];
        var max = arr[0];
        for (var i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        console.log('该数组里面的最大值是:' + max);
 // 利用函数求数组 [5,2,99,101,67,77] 中的最大数值。
        function getArrMax(arr) { // arr 接受一个数组  arr =  [5,2,99,101,67,77]
            var max = arr[0];
            for (var i = 1; i <= arr.length; i++) {
                if (arr[i] > max) {
                    max = arr[i];
                }
            }
            return max;
        }
        // getArrMax([5, 2, 99, 101, 67, 77]); // 实参是一个数组送过去
        // 在我们实际开发里面,我们经常用一个变量来接受 函数的返回结果 使用更简单
        // var re = getArrMax([5, 2, 99, 101, 67, 77]);
        var re = getArrMax([3, 77, 44, 99, 143]);
        console.log(re);
// 利用函数 求两个数的最大值
       function getMax(num1, num2) {
           return num1 > num2 ? num1 : num2;
       }
       console.log(getMax(1, 3));

007-计算数组的和以及平均值

示例代码:

  // 1. 求数组 [2,6,1,7, 4] 里面所有元素的和以及平均值。
        // (1)声明一个求和变量 sum。
        // (2)遍历这个数组,把里面每个数组元素加到 sum 里面。
        // (3)用求和变量 sum 除以数组的长度就可以得到数组的平均值。
        var arr = [2, 6, 1, 7, 4];
        var sum = 0;
        var average = 0;
        for (var i = 0; i < arr.length; i++) {
            sum += arr[i]; // 我们加的是数组元素 arr[i] 不是计数器 i
        }
        average = sum / arr.length;
        console.log(sum, average); // 想要输出多个变量,用逗号分隔即可

006-while循环案例

示例代码:

    // 1. 打印人的一生,从1岁到100岁
        var i = 1;
        while (i <= 100) {
            console.log('这个人今年' + i + '岁了');
            i++;
        }
        // 2. 计算 1 ~ 100 之间所有整数的和
        var sum = 0;
        var j = 1;
        while (j <= 100) {
            sum += j;
            j++
        }
        console.log(sum);

        // 3. 弹出一个提示框, 你爱我吗?  如果输入我爱你,就提示结束,否则,一直询问。
        var message = prompt('你爱我吗?');
        while (message !== '我爱你') {
            message = prompt('你爱我吗?');
        }
        alert('我也爱你啊!');

005-打印九九乘法表


示例代码:

   // 九九乘法表
        // 一共有9行,但是每行的个数不一样,因此需要用到双重 for 循环
        // 外层的 for 循环控制行数 i ,循环9次 ,可以打印 9 行  
        // 内层的 for 循环控制每行公式  j  
        // 核心算法:每一行 公式的个数正好和行数一致, j <= i;
        // 每行打印完毕,都需要重新换一行
        var str = '';
        for (var i = 1; i <= 9; i++) { // 外层循环控制行数
            for (var j = 1; j <= i; j++) { // 里层循环控制每一行的个数  j <= i
                // 1 × 2 = 2
                str += j + '×' + i + '=' + i * j + '\t';
            }
            str += '\n';
        }
        console.log(str);

004-打印倒三角形


示例代码:

    // 打印倒三角形案例
        var str = '';
        for (var i = 1; i <= 10; i++) { // 外层循环控制行数
            for (var j = i; j <= 10; j++) { // 里层循环打印的个数不一样  j = i
                str = str + '★';
            }
            str += '\n';
        }
        console.log(str);

003-打印n行n列的星星


示例代码:

      // 打印n行n列的星星
      var rows = prompt('请您输入行数:')
      var cols = prompt('请您输入列数:')
      var str = ''
      for (var i = 1; i <= rows; i++) {
        for (var j = 1; j <= cols; j++) {
          str += '★'
        }
        str += '\n'
      }
      console.log(str)

002-查询水果案例

示例代码:

//  弹出 prompt 输入框,让用户输入水果名称,把这个值取过来保存到变量中。
// 将这个变量作为 switch 括号里面的表达式。
// case 后面的值写几个不同的水果名称,注意一定要加引号 ,因为必须是全等匹配。
// 弹出不同价格即可。同样注意每个 case 之后加上 break ,以便退出 switch 语句。
// 将 default 设置为没有此水果。
var fruit = prompt('请您输入查询的水果:');
    switch (fruit) {
        case '苹果':
            alert('苹果的价格是 3.5/斤');
            break;
        case '榴莲':
            alert('榴莲的价格是 35/斤');
            break;
        default
            alert('没有此水果');
    }

001-判断闰年平年

示例代码:

//  算法:能被4整除且不能整除100的为闰年(如2020年就是闰年,1901年不是闰年)或者能够被 400 整除的就是闰年
// 弹出prompt 输入框,让用户输入年份,把这个值取过来保存到变量中
// 使用 if 语句来判断是否是闰年,如果是闰年,就执行 if 大括号里面的输出语句,否则就执行 else里面的输出语句
// 一定要注意里面的且 &&  还有或者 || 的写法,同时注意判断整除的方法是取余为 0
var year = prompt('请您输入年份:');
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
    alert('您输入的年份是闰年');
    } else {
        alert('您输入的年份是平年');
    }
  • 38
    点赞
  • 298
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值