Home Web Front-end JS Tutorial Example JavaScript to implement dynamic changes in numerical values

Example JavaScript to implement dynamic changes in numerical values

Nov 17, 2022 pm 04:01 PM
javascript

This article brings you relevant knowledge about JavaScript, which mainly introduces the relevant content on how to achieve dynamic changes in numerical values. Let's take a look at it together. I hope it will be helpful to everyone.

Example JavaScript to implement dynamic changes in numerical values

[Related recommendations: JavaScript video tutorial, web front-end]

The effect is as follows:

Example JavaScript to implement dynamic changes in numerical values


Without further ado, let’s go straight to the code:

HTML file:

  <div>
    <div>
      <i></i>
      <div></div>
      <span>常规赛总得分</span>
    </div>

    <div>
      <i></i>
      <div></div>
      <span>常规赛总篮板</span>
    </div>

    <div>
      <i></i>
      <div></div>
      <span>常规赛总助攻</span>
    </div>
  </div>
Copy after login

Code analysis:

Here I wrote a large container that contains three small containers. The data in each small container is displayed using data -*Attributes
(Note:data-* is used to store private custom data for a page or application, giving us the ability to embed ## on all HTML elements #Custom data attributeThe ability to store (custom) datacan be utilized in the page's JavaScript to create a better user experience (without making Ajax calls or server-side Database query)) Here we will pass in our customized data (
37062, 10210, 10045) so that it can be used in js Used in .


css file:

* {
    box-sizing: border-box;
  }
  
 .outer {
    background-color: #8e44ad;
    color: #fff;
    font-family: &#39;Roboto Mono&#39;, sans-serif;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 350px;
    overflow: hidden;
    margin: 0;
  }
  
  .counter-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    text-align: center;
    margin: 30px 50px;
  }
  
  .counter {
    font-size: 60px;
    margin-top: 10px;
  }
  
  @media (max-width: 580px) {
    .outer {
      flex-direction: column;
    }
  }
Copy after login

Code analysis:# The ##css file is very simple. It uses the

flex

layout, and finally adds a media query to adapt to changes in screen size. You can take a look at it yourself.


js file:

let counters = document.querySelectorAll(&#39;.counter&#39;)  //获取到三个counter盒子counters.forEach(item => {
    item.innerText = &#39;0&#39;  //记录分数变化的变量,初始值为0

    const updateData = () => {
        const data = +item.getAttribute(&#39;data-set&#39;)  //获取到元素中绑定的数据
        const tmp = +item.innerText //临时变量保存变化一次的数据量
    
        const changeData = data / 200  //设置改变的速率

        if(tmp < data) {  //如果临时变量的值小于最终数据的值,那么就给元素进行数据相加
            item.innerText = `${Math.ceil(tmp + changeData)}`  //值数相加,然后进行取整
            setTimeout(updateData,1)  //定时器传入回调函数目的在于动态变化
        } else {
            item.innerText = data  //不满足条件后,证明得到了最终数据,直接渲染
        }

    }
    updateData()  //调用函数,启动函数})
Copy after login

Code analysis:The dynamic change logic of data is here!

    First we need to
  • get the three divs

    that store the data, and then traverse the three boxes we got through the foreach method. The initial The score is 0, so we set the innerText of the box to 0 (note: 0 here is a string)

  • Then define a method to update data
  • updateData

    , and then obtain the data we customized before. Some friends here may be confused when they see item.getAttribute(data-set) Okay, why is the symbol in front? means that the following number is a positive number, which is equivalent to telling the compiler that the numerical type to be assigned is a numeric type, do not concatenate the numbers as strings

  • Then define a temporary variable
  • tmp

    , the purpose is to save the changed value in item.innerText, and then set the rate of data changeHere is Divided by 200, the divided data is approximately larger, then the slower the rate of change, and vice versa

  • Then make a judgment (let the temporary amount and the total amount do Comparison), if the temporary amount is less than the total amount, add the
  • temporary amount tmp

    and the data change amount changeData, and make a round. If the judgment condition is not met, the data will be rendered directly. But (the data at this time is already the final data, that is, our custom data)

  • To achieve dynamic changes in data, the core thing is
  • Timer

    , start the timer in the scope that meets the judgment conditions, pass in the callback function updateData, implement 1ms call once, the data changes look very smooth.


Written at the end:

If you follow the implementation logic of js step by step, you will find that the logic is very clear. I hope everyone can start step by step when writing js code. , otherwise it will be easy to mess up the logic. In the future, I will share with you some js
small demos, and let’s make some fun things together! While having fun, you can also improve your js development capabilities! 【Related recommendations:

JavaScript video tutorial

, web front-end

The above is the detailed content of Example JavaScript to implement dynamic changes in numerical values. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles