jQuery animate shake on hover

2019-06-06 02:21发布

问题:

I am attempting to make an element shake upon hover without using jQuery UI and have come across the following code, however I cant seem to figure out how to trigger on hover, this code has a Random effect and it confuses me every time I try to diffuse it. I'm trying to get them to animate one at a time not altogether

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:

Try this way:-

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

Refer this DEMO



回答2:

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