如何在 AngularJS 中动态增加/减少段落元素的高度

How do you increase/reduce the height of a paragraph element dynamically in AngularJS?

本文关键字:段落 元素 高度 增加 AngularJS 动态      更新时间:2023-09-26

当我单击"显示更多"按钮时,我需要增加 p 元素的高度,然后应该显示"显示更少",然后在我再次单击按钮时减小 p 元素的大小。在 Angular 中执行此操作的最佳方法是什么?

这是我的段落和按钮的结构——

<p ng-bind="MyController.notes"></p>
<button class="button show-button" ng-click="MyController.showMore()">Show More</button>

模板

 <div ng-init="more = false">
    <p ng-class="{'showMore': more, 'showLess': !more}">
        bla bla bla.
    </p>
    <button ng-click="more = !more">{{more ? 'Show Less' : 'Show More'}}</button>
 </div>

.CSS

 .showMore { height: auto; }
 .showLess { max-height: 100px; overflow: hidden }

我会使用ng-class指令。(此处的文档:https://docs.angularjs.org/api/ng/directive/ngClass)

所以这就像切换一个名为"showMore"的类,你需要在p元素中绑定它

<p ng-class="showMore">Stuff here</p>
<button ng-click="showMoreClick">{{ showMore ? 'Show Less' : 'Show More'}}</button>

在css中,只需使用showMore应用您想要的样式即可。 ng 类使用表达式工作,因此 showMore 要么是真的,要么是假的。在控制器中,您希望将单击按钮绑定到切换变量 show更多...像这样:

$scope.showMore(false) // initializing showMore to false (minimized first)
$scope.showMoreClick = function () {
    $scope.showMore(!$scope.showMore()); // toggle showMore
};