2012-05-19 90 views
1

我試圖做一個懸停時沒有使用jQuery UI的元素搖擺,並且遇到了下面的代碼,但是我似乎無法弄清楚如何觸發懸停,此代碼有一個隨機效果和每次我嘗試瀰漫時,它都會讓我感到困惑。我試圖讓他們在同一時間並非完全動畫一個懸停的jQuery動畫搖擺

http://jsfiddle.net/g6AeL/

$(function() { 
     var interval = 10; 
     var duration= 1000; 
     var shake= 3; 
     var vibrateIndex = 0; 
     var selector = $('aside.featured a'); /* Your own container ID*/ 
     $(selector).click(/* The button ID */ 

     function(){ 

     vibrateIndex = setInterval(vibrate, interval); 
     setTimeout(stopVibration, duration); 

     }); 

     var vibrate = function(){ 
     $(selector).stop(true,false) 
     .css({position: 'relative', 
     left: Math.round(Math.random() * shake) - ((shake + 1)/2) +'px', 
     top: Math.round(Math.random() * shake) - ((shake + 1)/2) +'px' 
     }); 
     } 

     var stopVibration = function() { 
     clearInterval(vibrateIndex); 
     $(selector).stop(true,false) 
       .css({position: 'static', left: '0px', top: '0px'}); 
      }; 

     }); 
+1

只是一個建議。您可以使用jQuery UI'shake'效果輕鬆完成此操作。檢查這個小提琴http://jsfiddle.net/joycse06/g6AeL/4/ –

回答

8

試試這個方法: -

$(function() { 
    var interval = 10; 
    var duration= 1000; 
    var shake= 3; 
    var vibrateIndex = 0; 
    var selector = $('.box'); /* Your own container ID*/ 
    $(selector).hover(/* The button ID */ 
     function(){ 
     vibrateIndex = setInterval(vibrate, interval);  
     }, 
     function(){ 
      clearInterval(vibrateIndex); 
      $(selector).stop(true,false) 
       .css({position: 'static', left: '0px', top: '0px'}); 
     } 
    ); 

    var vibrate = function(){ 
     $(selector).stop(true,false) 
     .css({position: 'relative', 
     left: Math.round(Math.random() * shake) - ((shake + 1)/2) +'px', 
     top: Math.round(Math.random() * shake) - ((shake + 1)/2) +'px' 
     }); 
    } 
}); 

請參閱本DEMO

+0

謝謝!只是好奇地動畫一次?是否必須通過父元素來完成? – iamwhitebox

+1

這裏你去http://jsfiddle.net/joycse06/g6AeL/10/ –

+0

achh!如此接近,非常感謝你今天早上我迷迷糊糊 - setInterval和ClearInterval行爲完全讓我困惑在這裏 – iamwhitebox

1

使用CSS

.item:hover { 
    animation: shake 0.82s cubic-bezier(.36,.07,.19,.97) both; 
    transform: translate3d(0, 0, 0); 
    backface-visibility: hidden; 
    perspective: 1000px; 
} 

@keyframes shake { 
    10%, 90% { 
    transform: translate3d(-1px, 0, 0); 
    } 

    20%, 80% { 
    transform: translate3d(2px, 0, 0); 
    } 

    30%, 50%, 70% { 
    transform: translate3d(-4px, 0, 0); 
    } 

    40%, 60% { 
    transform: translate3d(4px, 0, 0); 
    } 
} 
+0

美麗的更新回答,謝謝你 – iamwhitebox