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