前端笔记92——摆动效果以及摆动函数的封装

前言

在很多登录页面的框中,输入了错误的账户或者密码的时候,会出现摆动现象。那么这种摆动现象是怎么实现的呢?下面我来分享一下摆动效果的实例代码以及相关代码的封装。

摆动效果的实现
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			#box{
				width: 150px;
				height: 200px;
				background: #009F95;
				position:absolute;
				left: 400px;
				top: 100px;
			}
		</style>
	</head>
	<body>
		<div id="box"></div>
		<script type="text/javascript" ></script>
		<script type="text/javascript">
			var oBox = document.getElementById("box")
			oBox.onclick = function(){
				// 生成摆动的频率
				var arr = [];
				// 数组下标
				var index = 0
				for(var i = 30; i >=0; i -=3){
					 arr.push(i,-i)
				}
				clearInterval(oBox.waver)
				oBox.style.left = 400 +"px"
				oBox.waver = setInterval(function(){
					oBox.style.left = parseInt(getStyle(oBox,"left"))+arr[index] +"px"
					index++
					if(index===arr.length){
						clearInterval(oBox.waver)
					}
				},100)
			}
		</script>
	</body>
</html>
摆动效果的封装
/**
 * 功能:实现摆动的效果 
 * @param {type} obj 需要传一个对象
 * @param {type} direction 摆动的方向
 * @param {type} initValue 偏移多少px
 * @param {type} callback  代码回调
 */
function waver(obj,direction,initValue,callback) {
	// 生成摆动的频率
	var arr = [];
	// 数组下标
	var index = 0
	for(var i = 30; i >= 0; i -= 3) {
		arr.push(i, -i)
	}
	clearInterval(obj.waver)
	obj.style[direction] = initValue + "px"
	obj.waver = setInterval(function() {
		obj.style[direction] = parseInt(getStyle(obj, direction)) + arr[index] + "px"
		index++
		if(index === arr.length) {
			clearInterval(obj.waver)
			callback && callback()
		}
	}, 100)
}
摆动函数的调用
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			#box{
				width: 150px;
				height: 200px;
				background: #009F95;
				position:absolute;
				left: 400px;
				top: 100px;
			}
		</style>
	</head>
	<body>
		<div id="box"></div>
		// 引入封装函数的JS文件
		<script type="text/javascript" src="../js/tool.js" ></script>
		<script type="text/javascript">
			var oBox = document.getElementById("box")
			oBox.onclick = function(){
				waver(oBox,"top",100,function(){
					alert("密码错误")
				})
			}
		</script>
	</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值