使用angularjs将框移动到随机位置

col*_*oll 1 javascript animation angularjs

我正在寻找一种方法来使用angularjs 从这个答案中实现确切的功能:具体来说,一个盒子(div)在屏幕上随机移动,同时进行动画制作.目前我已经尝试过

myApp.directive("ngSlider", function($window) {
  return {
    link: function(scope, element, attrs){
        var animateDiv = function(newq) {
            var oldRect = element.getBoundingClientRect();
            var oldq = [oldRect.top, oldRect.left];
            if (oldq != newq){
                var dir = calcDir([oldq.top, oldq.left], newq);
                element.moveTo(oldq.left + dir[0], oldq.top + dir[1]);
                setTimeout(animateDiv(newq), 100);
            }
        };

        var makeNewPosition = function() {
            // Get viewport dimensions (remove the dimension of the div)
            var window = angular.element($window);
            var h = window.height() - 50;
            var w = window.width() - 50;

            var nh = Math.floor(Math.random() * h);
            var nw = Math.floor(Math.random() * w);

            return [nh,nw];

        };


        function calcDir(prev, next) {
            var x = prev[1] - next[1];
            var y = prev[0] - next[0];
            var norm = Math.sqrt(x * x + y * y);
            return [x/norm, y/norm];
        }
        var newq = makeNewPosition();
        animateDiv(newq);
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

从角度来看,这似乎有点不对劲.任何帮助表示赞赏.

小智 5

我喜欢在这种情况下利用CSS.

  • 绝对定位你的div
  • 用于ng-style绑定topleft属性到某个范围内变量
  • 随机更改此范围内变量的属性topleft属性
  • 使用CSS过渡topleft属性为您设置动画

我做了一个plnkr!访问肯塔基!