欢迎提供更好的方法!
<!--http://www.cnblogs.com/webzhangnan/p/3244920.html -->
<html>
<head>
<title>IOS shake by conan</title>
<style type="text/css">
.box{
display: -webkit-box;
padding: 20px;
}
.icon{
height: 100px;
width: 100px;
margin: 20px;
background: red;
}
#start{
width: 200px;
height: 60px;
line-height: 60px;
text-align: center;
margin: 10px;
border: 1px solid #ddd;
}
</style>
</head>
<body>
<div class="box">
<div class="icon"></div>
<div class="icon"></div>
<div class="icon"></div>
<div class="icon"></div>
</div>
<div id="start">run shake</div>
<script type="text/javascript">
shake = function($item) {
if ($item.length) {
var timeIdAry = [] , len = $item.length;
while(len--) timeIdAry.push(shake($item[len]));
return function() {
var stop;
while (stop = timeIdAry.shift()) {
stop();
}
}
} else {
var timeId, runing = true,
duration = '-webkit-transition: -webkit-transform 100ms;',
d = false;
var loop = function() {
if (!runing) return;
if(!$item.getAttribute('pause'))
$item.style.cssText = duration + '-webkit-transform: translate3d(' + (d ? 0 : 0) + 'px,' + (d ? 0 : 0) + 'px, 0) rotate(' + (d ? -1 : 1) + 'deg);-webkit-transform-origin: '+(d ? 20 : 80) + '% ' + (d ? 80 : 20) + '%'
d = !d;
timeId = setTimeout(loop, 100);
}
loop();
return function() {
clearTimeout(timeId);
$item.setAttribute('style', '');
delete $item;
loop = null;
itemId = runing = null;
}
}
}
var icons = document.querySelectorAll('.icon');
var stop;
document.querySelector('#start').addEventListener('click', function(){
if(stop) stop(),stop=null,this.innerHTML = 'run shake';
else stop = shake(icons), this.innerHTML = 'kill shake';
});
var s = icons.length , EV = 'ontouchstart' in window ? {start : 'touchstart',end:'touchend'} : {start : 'mouseover',end:'mouseout'};
while(s--){
icons[s].addEventListener(EV.start, function(e){
e.target.setAttribute('pause', 1);
e.target.setAttribute('style', '-webkit-transform: scale(1.5);-webkit-transition: -webkit-transform 100ms;opacity:.5');
});
icons[s].addEventListener(EV.end, function(e){
e.target.setAttribute('pause', '');
});
}
</script>
</body>
</html>