元素抖动函数封装
1.抖动封装
/*
op: {
el,
attr,
shakeLength
}
*/
function shake(op){
var el = op.el,
attr = op.attr,
shakeLength = op.shakeLength||15,
start = css(box,attr),
shakeArr = [];
for(var i = shakeLength; i >= 0; i--){
shakeArr.push(i%2?i:-i);
}
move();
function move(){
requestAnimationFrame(function(){
if(shakeArr.length <= 0){
console.log("抖动完成");
} else {
css(el,attr,start + shakeArr.shift());
console.log(1);
move();
}
});
}
}
(function(){
var box = document.querySelector("#box");
shake({
el: box,
attr: "width",
shakeLength: 20
});
})();
2.多值同时抖动
<script>
/*
op: {
el,
attr,
shakeLength
}
*/
function shake(op){
var el = op.el,
attr = op.attr,
shakeLength = op.shakeLength||15,
start = {},
shakeArr = [];
if(typeof attr === "object" ){
for(var i = 0; i < attr.length; i++){
start[attr[i]] = css(el,attr[i]);
}
} else {
start[attr] = css(el,attr);
}
for(var i = shakeLength; i >= 0; i--){
shakeArr.push(i%2?i:-i);
}
move();
function move(){
requestAnimationFrame(function(){
if(shakeArr.length <= 0){
console.log("抖动完成");
} else {
var nub = shakeArr.shift();
for(var s in start){
css(el,s,start[s] + nub);
}
move();
}
});
}
}
(function(){
var box = document.querySelector("#box");
shake({
el: box,
attr: ["width","height","opacity"],
shakeLength: 20
});
})();
</script>
3.抖动函数完整封装
<script>
/*
op: {
el,
attr,
shakeLength
}
*/
function shake(op){
var el = op.el,
attr = op.attr,
shakeLength = op.shakeLength||15,
shakeArr = [];
el.shakeStart = {};
if(el.shake) {
return ;
}
if(typeof attr === "object" ){
for(var i = 0; i < attr.length; i++){
el.shakeStart[attr[i]] = css(el,attr[i]);
}
} else {
el.shakeStart[attr] = css(el,attr);
}
for(var i = shakeLength; i >= 0; i--){
shakeArr.push(i%2?i:-i);
}
move();
function move(){
el.shake = requestAnimationFrame(function(){
if(shakeArr.length <= 0){
el.shake = false;
op.cb&&op.cb();
} else {
var nub = shakeArr.shift();
for(var s in el.shakeStart){
css(el,s, el.shakeStart[s] + nub);
}
move();
}
});
}
}
shake.stop = function(el){
cancelAnimationFrame(el.shake);
el.shake = false;
for(var s in el.shakeStart){
css(el,s, el.shakeStart[s]);
}
};
(function(){
var box = document.querySelector("#box");
box.onclick = function(){
shake.stop(box);
shake({
el: box,
attr: "left",
shakeLength: 20,
cb: function(){
mTween({
el: box,
attr: {
top: 500
},
duration: 1000,
fx: "bounceOut"
});
}
});
};
})();
</script>