jQuery反弹变化(反弹)

时间:2011-10-24 09:21:33

标签: jquery bounce

我正在努力为此找到一个插件/插件,这是我项目的一个关键部分,我忽略了它,现在它被我咬了。

我需要一个jQuery反弹的变体,这会使div在父div /包装器周围不稳定地反弹。

实际上,我将有一个屏幕,用户通过点击生成div,并在屏幕上浮动/反弹。

请帮我找一个插件或一些代码来解决这个问题。

非常感谢

1 个答案:

答案 0 :(得分:5)

我无法告诉你这对100个div有多敏感,但基于早期的脚本,这里至少可以让你开始 - http://jsfiddle.net/jgJsL/5/

$.fn.bounce = function(options) {

    var settings = $.extend({
        speed: 10
    }, options);

    return $(this).each(function() {

        var $this = $(this),
            $parent = $this.parent(),
            height = $parent.height(),
            width = $parent.width(),
            top = Math.floor(Math.random() * (height / 2)) + height / 4,
            left = Math.floor(Math.random() * (width / 2)) + width / 4,
            vectorX = settings.speed * (Math.random() > 0.5 ? 1 : -1),
            vectorY = settings.speed * (Math.random() > 0.5 ? 1 : -1);

        // place initialy in a random location
        $this.css({
            'top': top,
            'left': left
        }).data('vector', {
            'x': vectorX,
            'y': vectorY
        });

        var move = function($e) {

            var offset = $e.offset(),
                width = $e.width(),
                height = $e.height(),
                vector = $e.data('vector'),
                $parent = $e.parent();

            if (offset.left <= 0 && vector.x < 0) {
                vector.x = -1 * vector.x;
            }
            if ((offset.left + width) >= $parent.width()) {
                vector.x = -1 * vector.x;
            }
            if (offset.top <= 0 && vector.y < 0) {
                vector.y = -1 * vector.y;
            }
            if ((offset.top + height) >= $parent.height()) {
                vector.y = -1 * vector.y;
            }

            $e.css({
                'top': offset.top + vector.y + 'px',
                'left': offset.left + vector.x + 'px'
            }).data('vector', {
                'x': vector.x,
                'y': vector.y
            });

            setTimeout(function() {
                move($e);
            }, 50);

        };

        move($this);
    });

};

$(function() {
    $('#wrapper li').bounce({
        'speed': 7
    });
});