ng 重复上的随机高度



我想拥有随机高度的div。但是,我在 ng 样式中的随机高度函数只被调用一次,并将相同的随机高度应用于所有div

这是我的网页:

<div id = "{{result.myId}}"ng-repeat="result in results" ng-style = "resultBox" ng-click="loadDetails(result.myId)">
    <div ng-style="setImage(result.miThumbnail)"></div>
    <h5>{{result.name}}</h5>
</div>

.JS:

$scope.resultBox = {
            backgroundColor:'#ffffff',
            height: $scope.randomHeight(200)+'px',
            position:'relative',
            textAlign:'center',
            verticalAlign:'top',
            width:'260px',
            display:'inline-block',
            margin:'10px',
            borderRadius:'5px'
        };
 $scope.randomHeight = function(max){
            var height = Math.floor((Math.random()*max)+1);
            return height;
        };

问题是您的$scope.randomHeight(200)只运行一次并一遍又一遍地重用。尝试将$scope.resultBox转换为函数。

$scope.resultBox = function(){ 
        return {
            backgroundColor:'#ff0000',
            height: $scope.randomHeight(200)+'px',
            position:'relative',
            textAlign:'center',
            verticalAlign:'top',
            width:'260px',
            display:'inline-block',
            margin:'10px',
            borderRadius:'5px'
        };
       }

还要更改您的 html 以调用此函数:ng-style="resultBox()"

演示

尝试使用函数:

<div id = "{{result.myId}}"ng-repeat="result in results" ng-style = "resultBox()" ng-click="loadDetails(result.myId)">
    <div ng-style="setImage(result.miThumbnail)"></div>
    <h5>{{result.name}}</h5>
 </div>

   $scope.resultBox = function() {
        backgroundColor:'#ffffff',
        height: $scope.randomHeight(200)+'px',
        position:'relative',
        textAlign:'center',
        verticalAlign:'top',
        width:'260px',
        display:'inline-block',
        margin:'10px',
        borderRadius:'5px'
    };
    $scope.randomHeight = function(max){
        var height = Math.floor((Math.random()*max)+1);
        return height;
    };

最新更新