Random Movement in a Fixed Container

前端 未结 2 1306
死守一世寂寞
死守一世寂寞 2021-02-10 11:56

I\'m looking to create something that can move randomly inside of a fixed div container. I love the way the object moves in this example that I found searching this website...

相关标签:
2条回答
  • 2021-02-10 12:37

    Here is a jsfiddle with the functionality you're seeking: http://jsfiddle.net/2TUFF/

    JavaScript:

    $(document).ready(function() {
        animateDiv();
    
    });
    
    function makeNewPosition($container) {
    
        // Get viewport dimensions (remove the dimension of the div)
        $container = ($container || $(window))
        var h = $container.height() - 50;
        var w = $container.width() - 50;
    
        var nh = Math.floor(Math.random() * h);
        var nw = Math.floor(Math.random() * w);
    
        return [nh, nw];
    
    }
    
    function animateDiv() {
        var $target = $('.a');
        var newq = makeNewPosition($target.parent());
        var oldq = $target.offset();
        var speed = calcSpeed([oldq.top, oldq.left], newq);
    
        $('.a').animate({
            top: newq[0],
            left: newq[1]
        }, speed, function() {
            animateDiv();
        });
    
    };
    
    function calcSpeed(prev, next) {
    
        var x = Math.abs(prev[1] - next[1]);
        var y = Math.abs(prev[0] - next[0]);
    
        var greatest = x > y ? x : y;
    
        var speedModifier = 0.1;
    
        var speed = Math.ceil(greatest / speedModifier);
    
        return speed;
    
    }​
    

    HTML:

    <div id="container">
    <div class='a'></div>
    </div>​
    

    CSS:

    div#container {height:100px;width:100px;}
    
    div.a {
    width: 50px;
    height:50px;
     background-color:red;
    position:fixed;
    
    }​
    

    This will allow you to create a wrapping element with any height/width and have the floating element keep within its container's area.

    0 讨论(0)
  • 2021-02-10 12:39

    Add a wrapper element around it and update the jQuery to limit the dimensions.

    <div id="wrap">
        <div class='a'></div>
    </div>
    

    // Get viewport dimensions (remove the dimension of the div)
        var h = $('#wrap').height() - 50;
        var w = $('#wrap').width() - 50;
    

    Here's an updated fiddle: http://jsfiddle.net/Xw29r/375/

    0 讨论(0)
提交回复
热议问题