Implementing jQuery's shake effect with animate

前端 未结 9 2493
迷失自我
迷失自我 2020-12-14 10:38

I\'ve been given a cut down subset of the jQuery lib one of the key features I\'m missing is the .effect functions. I do however have .animate. I w

9条回答
  •  心在旅途
    2020-12-14 11:21

    Based on @el producer solution, I added some multiply logic and make it look like a random shake.

    jQuery.fn.shake = function (interval, distance, times) {
        interval = typeof interval == "undefined" ? 100 : interval;
        distance = typeof distance == "undefined" ? 10 : distance;
        times = typeof times == "undefined" ? 3 : times;
        var jTarget = $(this);
        jTarget.css('position', 'relative');
        for (var iter = 0; iter < (times + 1) ; iter++) {
            jTarget.animate({ top: ((iter % 2 == 0 ? distance * Math.random() : distance * Math.random() * -1)), left: ((iter % 2 == 0 ? distance * Math.random() : distance * Math.random() * -1)) }, interval);
        }
        return jTarget.animate({ top: 0 , left: 0 }, interval);
    }
    

提交回复
热议问题