可扩展 Div 是指可以通过用户交互(如点击按钮)来展开或收起内容的容器。在 AngularJS 中,我们可以利用其数据绑定和指令系统轻松实现这一功能。
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="toggleExpand()">
{{ isExpanded ? '收起' : '展开' }}
</button>
<div ng-show="isExpanded">
<!-- 可扩展的内容 -->
这里是可扩展的内容区域...
</div>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', function($scope) {
$scope.isExpanded = false;
$scope.toggleExpand = function() {
$scope.isExpanded = !$scope.isExpanded;
};
});
</script>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="toggleExpand()">
{{ isExpanded ? '收起' : '展开' }}
</button>
<div ng-class="{ 'expanded': isExpanded, 'collapsed': !isExpanded }">
<!-- 可扩展的内容 -->
这里是带有动画效果的可扩展内容...
</div>
</div>
<style>
.expanded {
height: auto;
max-height: 500px;
transition: max-height 0.5s ease-in;
overflow: hidden;
}
.collapsed {
max-height: 0;
transition: max-height 0.3s ease-out;
overflow: hidden;
}
</style>
<div ng-app="myApp">
<expandable-div title="点击展开">
这里是可扩展的内容...
</expandable-div>
</div>
<script>
angular.module('myApp', [])
.directive('expandableDiv', function() {
return {
restrict: 'E',
transclude: true,
scope: {
title: '@'
},
template: `
<div>
<button ng-click="toggle()">{{ isExpanded ? '收起' : title }}</button>
<div ng-show="isExpanded" ng-transclude></div>
</div>
`,
link: function(scope) {
scope.isExpanded = false;
scope.toggle = function() {
scope.isExpanded = !scope.isExpanded;
};
}
};
});
</script>
原因:高度变化导致周围元素重新布局 解决方案:
max-height
替代 height
overflow: hidden
transition
平滑过渡原因:事件冒泡导致父级 Div 也响应点击 解决方案:
$event.stopPropagation()
原因:初始渲染时内容尚未完全加载 解决方案:
$timeout
延迟高度计算通过以上方法和技巧,你可以轻松在 AngularJS 中实现功能完善、用户体验良好的可扩展 Div 组件。
没有搜到相关的文章