1

我试图在不使用 jQuery UI 的情况下使元素在悬停时摇晃,并且遇到了以下代码,但是我似乎无法弄清楚如何在悬停时触发,这段代码具有随机效果,每次我尝试时都会让我感到困惑扩散它。我试图让他们一次动画一个而不是完全

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'});
            };

        });
4

2 回答 2

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'
        });
    }
});

参考这个演示

于 2012-05-19T14:31:07.477 回答
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);
  }
}
于 2016-10-13T14:00:16.190 回答