【问题标题】:Moving a box to a random position with angularjs使用angularjs将盒子移动到随机位置
【发布时间】:2014-03-20 19:35:57
【问题描述】:

我正在寻找一种方法来使用 angularjs 实现 this answer 的确切功能:具体来说,让一个框 (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);
    }
  };
});

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

【问题讨论】:

    标签: javascript angularjs animation


    【解决方案1】:

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

    • 绝对定位您的 div
    • 使用ng-styletopleft 属性绑定到某个范围内的变量
    • 随机更改此范围内变量的topleft 属性
    • topleft 属性上使用 CSS 过渡来为您制作动画

    我发了plnkr!访问肯塔基!

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 2021-02-23
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多