我的柜台编号动画无法正常运作?

如何解决我的柜台编号动画无法正常运作?

我使用Math.random()用随机数创建了计数器数字功能。我已经编写了如下代码,但是仍然有些事情无法正常进行。我有几个数字,例如200 1.91500。问题是,当运行其他数字时,动画将运行,但是在数字1.9中,动画将不起作用。而且,速度还能进一步降低吗?

我创建的代码在哪里缺失或错误?

// function for count statistic
function countNumber() {

$('.count').each(function() {

var countTo = Number($(this).text())

$(this).prop('Counter',0).animate({
     Counter: countTo - 1
},{
     duration: 2000,easing: 'swing',step: function(now) {
     var ceil = Math.floor(Math.random() * Math.floor(now))
         if (ceil < countTo) {
         $(this).text(ceil);
     }
     },complete: function() {
         $(this).text(countTo);
     }
  });
 });
}

$(document).ready(function() {
  countNumber();
});
#countAnimation {
  display: flex;
  justify-content: space-between;
  margin-bottom:200px;
}

.box-counter {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #cacaca;
  color: #0f0f0f;
  width: 150px;
  height: 150px;
  border-radius: 50%;
  box-shadow: 0px 6px 12px rgba(0,0.16);
  font-size: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div id="countAnimation">
  <div class="box-counter">
    <div class="count">200</div>
  </div>
  <div class="box-counter">
    <div class="count">1.9</div>
  </div>
  <div class="box-counter">
    <div class="count">1500</div>
  </div>
</div>

解决方法

问题在于您已将每个动画从0设置为countTo - 1。对于1.9,这意味着它将缓慢地从0过渡到0.9,并且在每一步中,您将随机数乘以0和{{ 1}}:

0.9

,它将始终为var ceil = Math.floor(Math.random() * Math.floor(now))。然后,将其设置为0(如果较低)作为文本的值(之所以会一直是因为它始终为0)。

0

设置if (ceil < countTo) { $(this).text(ceil); } 变量时,最好的做法可能是不要降低now

如果您担心结果数字中会有很多多余的数字,请尝试在if条件之后使用.toFixed():

https://www.w3schools.com/jsref/jsref_tofixed.asp

将步进功能更改为此:

ceil
,

代码正常运行。首先,您可以通过更改{duration:5000,}来更改计数器速度,每1000秒为1秒。其次,1.9值不能以1500的等速动画。这就是为什么动画几乎完成后才运行的原因。尝试将值更改为更大的数字。 让我知道这是否可以解决您的问题。

const DispensingIncidents = (props) => {
  const classes = useStyles();
  const {
    getFilterData,dispensingData,getOverviewData,location,history,getAnalysis,} = props;

  const [timeSpan,setTimeSpan] = React.useState("monthly");
  const [year,setYear] = React.useState(2020);
  const [tabValue,setTabValue] = React.useState(0);
  const [spanData,setSpanData] = React.useState([]);
  const [dataType,setDataType] = React.useState("");
  const [dataTo,setDataTo] = React.useState("");
  const [dataFrom,setDataFrom] = React.useState("");

  // eslint-disable-next-line
  const [overViewDataType,setOverViewDataType] = React.useState("");

  const {
    loading,duration,period,type,dispensingOverviewData,overviewDataLoading,incidenceAnalysisData,analysisDataLoading,} = dispensingData;
  const { count } = dispensingOverviewData;
  const { monthly } = duration;
  useEffect(() => {
    history.replace({
      pathname: location.pathname,search: `?year=${year}&period=${timeSpan}`,});
    setYear(year);
    setTimeSpan(timeSpan);
    // eslint-disable-next-line
  },[year,timeSpan]);

  /**
   *  This updates on Year given
   */
  useEffect(() => {
    getFilterData(year);
  },[getFilterData,year]);
  // console.log("DispesningDuration",monthly[0]);    <--- this gives the data 
  useEffect(() => {
    getOverviewData(
      Object.keys(period)[3],monthly[0].period.to,<--- Here it says [0] is not defined
      monthly[0].period.from,Object.keys(type)[0]
    );

    setTimeSpan(Object.keys(period)[3]);
    setDataFrom(monthly[0].period.from);
    setDataTo(monthly[0].period.to);
    setDataType(Object.keys(type)[0]);
  },[getOverviewData,monthly,type]);

  useEffect(() => {
    getAnalysis(
      count[0].key,Object.keys(period)[3],monthly[0].period.from,Object.keys(type)[0],1
    );
    setOverViewDataType(count[0].key);
  },[count,monthly]);

  /**
   * GET query from url search param
   *  @usage query.get("year")
   */
  function useQuery() {
    return new URLSearchParams(location.search);
  }
  const query = useQuery();
  const time = query.get("period");
  useEffect(() => {
    if (time === "yearly") {
      const yearlyData = duration["yearly"];
      setSpanData(yearlyData);
    } else if (time === "weekly") {
      const weeklyData = duration["weekly"];
      setSpanData(weeklyData);
    } else if (time === "quarterly") {
      const quarterlyData = duration["quarterly"];
      setSpanData(quarterlyData);
    } else if (time === "monthly") {
      const monthlyData = duration["monthly"];
      setSpanData(monthlyData);
    } else if (time === "6 months") {
      const halfYearlyData = duration["half-yearly"];
      setSpanData(halfYearlyData);
    }
  },[time,duration]);

  /**
   *
   * @param {*} event
   * @param {*} newValue
   * on tab change
   */

  // eslint-disable-next-line
  const handleTabChange = (event,newValue) => {
    setTabValue(newValue);
  };

  /**
   * Year change
   * @param {*} event
   */
  const handleYearChange = (event) => {
    setYear(event.target.value);
    setTimeSpan(query.get("period"));
  };

  /**
   * Span change
   * @param {*} event
   */
  const handleSpanChange = (event) => {
    const value = event.target.value;
    setTimeSpan(value);
  };

  const handleSpanTabChange = (data) => {
    setDataTo(data.period.to);
    setDataFrom(data.period.from);
    getOverviewData(time,data.period.to,data.period.from,dataType);
  };
  const handleDataTypeChange = (event) => {
    setDataType(event.target.value);
    getOverviewData(time,dataTo,dataFrom,event.target.value);
  };

  const handleOverViewClick = (data) => {
    getAnalysis(data,time.toLowerCase(),dataType,1);
  };
// function for count statistic
function countNumber() {

$('.count').each(function() {

var countTo = Number($(this).text())

$(this).prop('Counter',0).animate({
     Counter: countTo - 1
},{
     duration: 5000,easing: 'swing',step: function(now) {
     var ceil = Math.floor(Math.random() * Math.floor(now))
         if (ceil < countTo) {
         $(this).text(ceil);
     }
     },complete: function() {
         $(this).text(countTo);
     }
  });
 });
}

$(document).ready(function() {
  countNumber();
});
#countAnimation {
  display: flex;
  justify-content: space-between;
  margin-bottom:200px;
}

.box-counter {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #cacaca;
  color: #0f0f0f;
  width: 150px;
  height: 150px;
  border-radius: 50%;
  box-shadow: 0px 6px 12px rgba(0,0.16);
  font-size: 50px;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-