div标签溢出时添加类

时间:2016-09-07 09:03:34

标签: javascript html css angularjs css3

我有一个div具有固定的高度和宽度,我使用ng-repeat在其中添加了一些内容,我想在这个div溢出时添加一个类。我尝试使用length添加课程,但没有工作。



var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
  $scope.placeholder = ['Koenigsegg CCXR Trevita',
    'Lamborghini Veneno',
    'W Motors Lykan Hypersport',
    'Bugatti Veyron',
    'Ferrari Pininfarina Sergio',
    'Pagani Huayra BC',
    'Ferrari F60 America',
    'Bugatti Chiron',
    'Koenigsegg One',
    'Koenigsegg Regera'
  ];
});

div {
  height: 40px;
  width: 400px;
  background: #f2f2f2;
  padding: 5px;
}
span {
  border: 1px solid #999;
  padding: 3px;
  display: inline-block;
  margin: 2px;
  border-radius: 3px;
}

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<div ng-app="myApp" ng-controller="personCtrl">
  <span ng-repeat="j in placeholder;">
    {{j}} &times;
  </span>

</div>
&#13;
&#13;
&#13;

注意:我只能使用javascriptangularjs

1 个答案:

答案 0 :(得分:1)

如果只需要在数组中有太多项时添加一些类,则可以使用ng-class属性。

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {

});
&#13;
div{height:100px;width:100px;background:#f2f2f2;border:1px solid #000}
div.too-long {background-color: #FF6666}
&#13;
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<div ng-app="myApp" ng-controller="personCtrl" ng-class="{'too-long': placeholder.length > 6}" ng-init="placeholder=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]">
  <span ng-repeat="j in placeholder;">
    {{j}} Content
  </span>

</div>
&#13;
&#13;
&#13;

但是如果你需要比较内容大小和div大小,你可以使用div的offsetHeight和scrollHeight属性

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope, $element) {
    $scope.placeholder = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
    $scope.overflow = function() {
        return $element[0].scrollHeight > $element[0].offsetHeight;
    }
});
&#13;
div{height:100px;width:100px;background:#f2f2f2;border:1px solid #000}
div.too-long {background-color: #FF6666}
&#13;
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<div ng-app="myApp" ng-controller="personCtrl" ng-class="{'too-long': overflow()}">
  <span ng-repeat="j in placeholder;">
    {{j}} Content
  </span>

</div>
&#13;
&#13;
&#13;