2014-02-20 27 views
2

我正在寻找一种方法来使用angularjs从this answer实现确切的功能:具体来说,为一个框(div)在屏幕上随机移动,同时被动画。目前我已经尝试过将框移动到随机位置与angularjs

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

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

回答

5

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

  • 绝对定位的DIV
  • 使用ng-styletopleft属性绑定到某些范围的变量
  • 随意改变的topleft属性本调查范围内的可变
  • 使用CSS过渡上topleft属性为您设置动画效果

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