• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Javascript以和定时器,实现案例 | 青训营

武飞扬头像
龙猫446
帮助1

下面我先介绍window定时器方法,然后利用JavaScript,并且结合定时器,展示几个完整的小案例。

(1)像手机上的拼夕夕一样,弹出消息提示;

(2)还有模拟点“×”,关闭弹窗广告;

(3)模拟网页淘宝,鼠标与侧边栏的互动;

(4)实现切换标签栏的功能。

接下来进入正题。


1_window定时器方法

计划调用(scheduling a call):某些情况不想立即执行一个函数,而是等待特定一段时间之后再执行

两种方式实现:

  • setTimeout 允许将函数推迟到一段时间间隔之后再执行。
  • setInterval 允许重复运行一个函数,从一段时间间隔之后开始运行,之后以该时间间隔连续重复运行该函数。

有对应的取消方法:

  • clearTimeout:取消setTimeout的定时器;
  • clearInterval:取消setInterval的定时器;

大多数运行环境都有内置的调度程序,并提供这些方法:

  • 目前,所有浏览器以及 Node.js 都支持这两个方法;

  • 后续学习Node的时候,可以使用它们;

1.1_setTimeout

语法:let timerId = setTimeout( func | code , [ delay ] , [ arg1 ],[ arg2 ],...)

  • 只执行一次
  • func|code:想要执行的函数或代码字符串。 一般传入的都是函数,由于某些历史原因,支持传入代码字符串,但是不建议这样做;
  • delay:执行前的延时,以毫秒为单位(1000 毫秒 = 1 秒),默认值是 0;
  • arg1,arg2…:要传入被执行函数(或代码字符串)的参数列表;

clearTimeout:在调用时会返回一个“定时器标识符(timer identifier)”,使用它来取消执行

1.2_setInterval

语法:let timerId = setInterval( func | code , [ delay ] , [ arg1 ],[ arg2 ],...)

  • 每间隔给定的时间周期性执行
  • func|code:想要执行的函数或代码字符串。 一般传入的都是函数,由于某些历史原因,支持传入代码字符串,但是不建议这样做;
  • delay:执行前的延时,以毫秒为单位(1000 毫秒 = 1 秒),默认值是 0;
  • arg1,arg2…:要传入被执行函数(或代码字符串)的参数列表;

clearInterval:返回一个“定时器标识符(timer identifier)”,通过clearInterval来取消这个定时器

<body>

  <button class="out">取消setTimeout定时器</button>
  <button class="itv">取消setInterval定时器</button>
  
  <script>

    // 1.setTimeout
    function foo(name, age, height) {
      console.log("foo被调用----", name, age, height)
    }
    var timeoutID = setTimeout(foo, 3000, "hihi", 18, 1.88)

    var timeoutBtn = document.querySelector(".out")
    timeoutBtn.onclick = function() {
      // 取消调度
      clearTimeout(timeoutID)
    }

    // 2.setInterval
    function bar() {
      console.log("bar被调用    ")
    }

    var itvID = setInterval(bar, 3000)

    var itvBtn = document.querySelector(".itv")
    itvBtn.onclick = function() {
      clearInterval(itvID)
    }

  </script>

</body>

2_案例 – 轮播消息提示

学新通

<style>
    .tip-bar {
      display: inline-flex;
      align-items: center;
      height: 30px;
      background-color: rgba(0,0,0,.4);
      border-radius: 16px;
    }
    img {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      margin-right: 5px;
    }
    span {
      font-size: 13px;
      color: white;
      margin-right: 8px;
    }
  </style>

<body>
  
  
  <div class="tip-bar">
    <img src="https://bfs.biyao.com/group1/M01/A2/67/rBACVGA_iOuAYaTxAAAPbted3yE165.png" alt="">
    <span>183***138对这件商品感兴趣</span>
  </div>

  <script>
    // 1.从服务器拿到数据ajax/fetch请求
    let tipList = [
      {
        icon: 'https://bfs.biyao.com/group1/M01/A6/97/rBACYWBCHqyAFH5tAAANZXX5Eww646.png',
        title: 'haha对这件商品感兴趣'
      },
      {
        icon: 'https://bfs.biyao.com/group1/M01/A2/67/rBACVGA_iOuAYaTxAAAPbted3yE165.png',
        title: '123***814对这件商品感兴趣'
      },
      {
        icon: 'https://bfs.biyao.com/group1/M00/7F/4E/rBACYV16HseAP-PnAAAW9bbVoKE463.png',
        title: '刘军对这件商品感兴趣'
      }
    ]

    // 2.动态的切换数据
    // 2.1.获取元素
    var tipBar = document.querySelector(".tip-bar")
    var imgEl = tipBar.querySelector("img")
    var spanEl = tipBar.querySelector("span")

    // 2.2.3s切换一次数据
    var currentIndex = 0 // 记录当前展示到的索引位置
    setInterval(function() {
      // 1> 根据索引获取item
      var tipItem = tipList[currentIndex]

      // 2> 给DOM设置内容
      imgEl.src = tipItem.icon
      spanEl.textContent = tipItem.title
      
      // 3> 重新计算索引
      currentIndex  
      if (currentIndex === tipList.length) {
        currentIndex = 0
      }
    }, 3000)

    // 随机
    // Math.floor(Math.random() * tipList.length)

  </script>

</body>


3_案例 – 关闭隐藏消息

学新通

<style>
    .top-bar {
      display: flex;
      flex-direction: row;
      align-items: center;
      height: 45px;
      width: 375px;
      background-color: black;
      /* 关键 动画*/
      overflow: hidden;
      transition: all .5s ease-out;
    }
    .delete {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      height: 100%;
      width: 30px;
      cursor: pointer;
    }
    .delete img {
      height: 10px;
      width: 10px;
    }
    .logo {
      height: 30px;
      width: 30px;
      margin-left:3px;
      margin-right: 30px;
      cursor: pointer;
    }
    span {
      color: white;
      font-size: 14px;
      flex: 1;

      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .btn {
      width: 94px;
      height: 100%;
      line-height: 45px;
      text-align: center;
      font-size: 14px;
      color: #fff;
      background-color: #F63515;
    }
  </style>

<body>
  
  <div class="top-bar">
    <div class="delete">
      <img src="./img/delete.png" alt="">
    </div>
    <img class="logo" src="./img/logo.png" alt="">
    <span>打开京东App,购物更轻松</span>
    <div class="btn">立即打开</div>
  </div>

  <script>
    // 1.获取元素
    var topBar = document.querySelector(".top-bar")
    var deleteEl = topBar.querySelector(".delete")

    // 2.监听delete的点击
    deleteEl.onclick = function() {
        //只是把高度归零,但是代码存在
      topBar.style.height = 0
        //下面这种方法不推荐,人为依赖于css样式动画的时间
      // setTimeout(function() {
      //   topBar.remove()
      // }, 300)
    }

    // 3.监听过渡动画结束   【推荐使用】 不用人为依赖时间
    topBar.ontransitionend = function() {
        //直接把代码移除
      topBar.remove()
    }

  </script>

</body>

4_案例 – 侧边栏展示

学新通

  <style>
    .tool-bar {
      position: fixed;
      top: 30%;
      right: 0;

      display: flex;
      flex-direction: column;
      align-items: center;

      width: 35px;
    }

    .item {
      position: relative;
      width: 35px;
      height: 35px;
      margin-bottom: 1px;
      
      background-color: #7a6e6e;
      border-radius: 3px 0 0 3px;
    }

    .icon {
      display: inline-block;
      width: 100%;
      height: 100%;
      cursor: pointer;
      background-image: url(./img/toolbars.png);
    }

    /*原始方法,在CSS设置
     .icon01 {
      background-position: -48px 0;
    }
    .icon02 {
      background-position: -48px -50px;
    }
    .icon03 {
      background-position: -48px -100px;
    }
    .icon04 {
      background-position: -48px -150px;
    } */

    .name {
      position: absolute;
      z-index: -1;
      right: 35px;
      /* left: -62px; */
      top: 0;
      
      width: 0;
      height: 35px;
      line-height: 35px;

      color: #fff;
      text-align: center;
      font-size: 12px;
      background-color: #7a6e6e;
      cursor: pointer;

      border-radius: 3px 0 0 3px;
      transition: width .2s ease;
    }

    .item:hover,
    .item:hover .name {
      background-color: #cd1926;
    }
  </style>

<body>
  
  <div class="tool-bar">
    <div class="item">
      <i class="icon icon01"></i>
      <div class="name">购物车</div>
    </div>
    <div class="item">
      <i class="icon icon02"></i>
      <div class="name">收藏</div>
    </div>
    <div class="item">
      <i class="icon icon03"></i>
      <div class="name">限时活动</div>
    </div>
    <div class="item">
      <i class="icon icon04"></i>
      <div class="name">大礼包</div>
    </div>
  </div>

  <script>
      //改进方法
    // 1.for循环 动态给icon设置backgroundPosition
    var iconEls = document.querySelectorAll(".icon")
    for (var i = 0; i < iconEls.length; i  ) {
      var iconEl = iconEls[i]
      iconEl.style.backgroundPosition = `-48px -${50*i}px`
    }

    // 2.实现鼠标进入动画
    // 方案一: mouseenter(不能使用事件委托) 【推荐】
    var itemEls = document.querySelectorAll(".item")
    for (var itemEl of itemEls) {
      itemEl.onmouseenter = function() {
        var nameEl = this.children[1]
        nameEl.style.width = "62px"
      }
      itemEl.onmouseleave = function() {
        var nameEl = this.children[1]
        nameEl.style.width = "0"
      }
    }

    // 方案二: mouSEO((Search Engine Optimization))ver(使用事件委托)
    // var toolbarEl = document.querySelector(".tool-bar")
    // toolbarEl.onmouSEO((Search Engine Optimization))ver = function(event) {
    //   handleMouseEvent(event, 62)
    // }
    // toolbarEl.onmouSEO((Search Engine Optimization))ut = function(event) {
    //   handleMouseEvent(event, 0)
    // }

    // function handleMouseEvent(event, width) {
    //   if (event.target !== toolbarEl) {
    //     // var itemEl = event.target.classList.contains("item") ? event.target: event.target.parentElement
    //     // 1.获取唯一的item
    //     var itemEl = null
    //     if (event.target.classList.contains("item")) {
    //       itemEl = event.target
    //     } else {
    //       itemEl = event.target.parentElement
    //     }

    //     // 2.根据item获取nameElement
    //     var nameEl = itemEl.children[1]

    //     // 3.设置宽度
    //     nameEl.style.width = `${width}px`
    //   }
    // }

  </script>

</body>

5_案例 - tabControl切换标签栏

学新通

  <link rel="stylesheet" href="./css/reset.css">
  <link rel="stylesheet" href="./css/common.css">
  <style>
    .main .section-content {
      display: flex;
      justify-content: space-between;
    }

    .main .section-content .left-content {
      width: 872px;
      height: 1000px;
    }
    .main .section-content .right-content {
      width: 295px;
      height: 500px;
    }
  </style>

<body>
  
  <div class="main main_wrapper">
    <div class="section-content">
      <div class="left-content">
        <div class="content-center">
          <div class="section_header">
            <div class="header_left">
              <h3 class="title">内容中心</h3>
            </div>
            <div class="header_right" href="#">
              <a class="more" href="#">更多</a>
            </div>
          </div>
          <div class="tab_control">
            <div class="item active">精品栏目</div>
            <div class="line"></div>
            <div class="item">赛事精品</div>
            <div class="line"></div>
            <div class="item">英雄攻略</div>
          </div>
        </div>
    </div>
  </div>

  <script>
    // 1.获取元素
    var tabControl = document.querySelector(".tab_control")

    // 2.监听鼠标进入(事件委托)
    var activeLiEl = tabControl.querySelector(".active")
    tabControl.onmouSEO((Search Engine Optimization))ver = function(event) {
      // 1.拿到事件发生的对象
      var itemEl = event.target
      if (itemEl.classList.contains("item")) {           
        // 方案一 for循环所有的item
        // 方案二 querySelector(".active")
        // 方案三 变量记录当前的active对应的item【推荐】
           // 取消其他的active
        activeLiEl.classList.remove("active")

        // 当前进入的item变成active
        itemEl.classList.add("active")

        // 将最新的itemEl变成activeLiEl
        activeLiEl = itemEl
      }
    }

  </script>
</body>

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgiijfi
系列文章
更多 icon
同类精品
更多 icon
继续加载