动画函数封装之 将函数封装到单独JS文件里面

以后经常使用这个函数的话,可以单独封装到一个Js文件,使用时引用即可。

1.单独新建一个js文件

2.直接引用

<script type="text/javascript" src="animate.js"></script>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.sliderbar {
				position: fixed;
				right: 0;
				bottom: 100px;
				width: 40px;
				height: 40px;
				line-height: 40px;
				text-align: center;
				color: #fff;
				cursor: pointer;
				background-color: skyblue;
			}
			
			.con {
				position: absolute;
				left: 0;
				top: 0;
				width: 200px;
				height: 40px;
				background-color: skyblue;
				z-index: -1; /* 这里设置为-1的原因就是让箭头压在con的上边 否则con移动过去之后会压住箭头 箭头就看不到了 */
			}
		</style>
	</head>
	<body>
		<div class="sliderbar">
			<span>←</span>
			<div class="con">问题反馈</div>
		</div>
		<script type="text/javascript">
			var sliderbar = document.querySelector('.sliderbar');
			var con = document.querySelector('.con');
			var span = document.querySelector('span');
			//鼠标经过sliderbar 就会让con这个盒子滑动到左侧
			//鼠标离开sliderbar 就会让con这个盒子滑动到右侧
			sliderbar.addEventListener('mouseenter', function() {
				animate(con, -160, function() {
					span.innerHTML = '→';
				});
			});
			sliderbar.addEventListener('mouseleave', function() {
				animate(con, 0, function() {
					span.innerHTML = '←';
				});
			})
		</script>
	</body>
</html>

animate.js:

function animate(obj, target,callback) {
				// console.log(callback);  //callback = function() {}
				clearInterval(obj.timer);
				obj.timer = setInterval(function() {
					var step = (target - obj.offsetLeft) / 10;
					//这里在进位时 负数应该往小取 整数应该往大取
					step = step > 0 ? Math.ceil(step) : Math.floor(step);
					if(obj.offsetLeft == target) {
						clearInterval(obj.timer);
						if(callback) {
							callback();
						}
					}
					//这里会产生小数,所以最后移动到的并不是实际我们想要的位置,有一点小的偏差 因此在上边我们对其进行取整
					obj.style.left = obj.offsetLeft + step + 'px';
				},15);
				
			}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hcoke

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值