每天学一个jquery插件-滚动的数字

每天一个jquery插件-滚动的数字

滚动的数字

啊,大海,你有有那么多~

一个超级简单的数字滚动特效,纯粹的滚动,当然万物皆可封装,这个小特效也能直接调用就能实现效果
在这里插入图片描述
大概过程就是,首先知道容器内的数字,然后知道预设变化的间隔,接着计算出步幅,完事定时器疯狂增与改,改到目标时间最后把原来的值放回来就好了,虽然多了点事但是前面的步骤我认为还是需要,毕竟这样才能让观察者感觉这个数字变化不是无序而是从小递增变到目标值得,有点期待感,不然一下99999一下1,那看着的感觉真的不是一种心情。

代码部分

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>数字的滚动</title>
		<script src="js/jquery-3.4.1.min.js"></script>
		<style>
			#div1 {
     
     
				border: 1px solid lightgray;
				width: 300px;
				height: 200px;
				margin: 20px;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			#div2 {
     
     
				border: 1px solid lightgray;
				width: 100px;
				height: 70px;
				margin: 20px;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		</style>
	</head>
	<body>
		<div id="div1">99999</div>
		<div id="div2">1234567</div>
	</body>
</html>
<script>
	$(function() {
     
     
		szdgd("div1").show();
		szdgd("div2").show(40);
	})


	var szdgd = function(id) {
     
     
		var $obj = $("#" + id);
		return {
     
     
			$obj:$obj,
			temp: 0,
			show: function(t) {
     
      //效果暂时定为五秒钟持续时长的,参数提供选择变化速度
				var that = this;
				t = t==undefined?30:t;
				that.temp  =parseInt(that.$obj.text());//记住原本的值
				var count = parseInt(5000/t);
				var span  = parseInt(that.temp/count)
				console.log(count,span)
				var count0 = 0;
				var temp0 = 0;
				var si = setInterval(function(){
     
     
					count0++;
					temp0+=span;
					that.settemp(temp0)
					if(count0>count){
     
     
						clearInterval(si);
						that.settemp(that.temp)
					}
				},t)
			},
			settemp: function(temp) {
     
     
				var that = this;
				that.$obj.text(temp);
			}
		}
	}
</script>

猜你喜欢

转载自blog.csdn.net/weixin_44142582/article/details/112253355