像这样? (可能更有效,但我试图保持你原来的结构)
<script>
var app = angular.module('keycount', []);
app.controller('keycountcontroller', function($scope, $log, $http) {
$scope.width = 500;
$scope.height = 500;
$scope.calc = function() {
var x = $scope.width;
var y = $scope.height;
var parent = $('#myCanvas');
while (x > 1) {
x = x / 2;
y = y / 2;
var child = $(parent).clone(false)[0];
$(child).css('width', x);
$(child).css('height', y);
$(child).css('position', 'relative');
$(child).css('top', y/2);
$(child).css('left', x/2);
$(parent).append(child);
parent = child;
//alert(x);
}
}
$scope.calc();
});
</script>
</head>
<body ng-controller="keycountcontroller">
<div id="myCanvas" style="border:1px solid #000000; width:{{width}}px; height:{{height}}px;"></div>
</body>
首先我认为使用指令会使它变得更好,肯定更令人印象深刻,但不会更有效。因此,这里有一个更紧凑的版本:
<script>
var app = angular.module('keycount', []);
app.controller('keycountcontroller', function($scope, $timeout) {
$scope.width = 300;
$scope.height = 300;
$scope.calc = function() {
var x = $scope.width;
var y = $scope.height;
var parent = $('#myCanvas');
while (x > 1) {
var child = $(parent).clone(false).css({ width: x = x / 2, height: y = y / 2, position: 'relative', top: x/2, left: y/2 });
$(parent).append(child);
parent = child;
}
}
});
</script>
</head>
<body ng-controller="keycountcontroller" ng-init="calc()">
<div id="myCanvas" style="border:1px solid #000000; width:{{width}}px; height:{{height}}px;"></div>
</body>