Angular:为父级div元素设置动态高度

3
我有以下情景:
 <div class="parent" style="height:100%">
        <div class="left" style="float:left" dynamic-height element-id="{{$index}}">
        </div>
        <div class="right" style="float:left">
            <div>Element 1</div>
            <div>Element 2</div>
    </div>
    </div>

我可以帮您翻译成中文。该段内容是关于编程的,作者想让左侧元素与右侧元素或父元素在同一高度上,他尝试使用指令来实现,但效果不佳,有没有更好的建议?
指令如下:
.directive('dynamicHeight', function() {
    return {
        compile: function compile(tElement, tAttrs, transclude) {
            return {
                post: function postLink(scope, elem, attrs) {
                    var element = "#discussion-element-"+ attrs.elementId;
                    var myEl = angular.element( document.querySelector( element) );
                    var height = myEl[0].offsetHeight;
                    element.height(height);
                }
            }
        }
    };
});

阐述问题的图像:

enter image description here


2
你可以尝试将这个问题作为CSS问题来解决,而不是AngularJS问题。在Google上搜索“css equal height columns”会有不同的方法。 - dfsq
2个回答

2
尝试移除 float: left 样式,并改为应用以下样式:
.parent {
    display: table;
}

.parent > * {
    display: table-cell;
}

1

最好在CSS中完成

正如评论所说,您可以使用CSS来实现此功能。(例如https://css-tricks.com/fluid-width-equal-height-columns/


如果你仍然想要使用Angular

你可以在指令的作用域内添加一个$watch,以便在父元素的width & height发生变化时得到回调。从那里,你可以改变元素的高度。

HTML

<div class="container demo">
    <div ng-controller="MyCtrl">
        <div>
            <button class="btn btn-primary" ng-click="isLarger = !isLarger">toggle parent size</button>
        </div>
        <hr>
        <div class="parent" ng-class="{'larger':isLarger}">
            <div class="child" dynamic-height>{{message}}</div>
        </div>
    </div>
</div>

JavaScript
var app = angular.module('myApp', []);

app.controller('MyCtrl', function ($scope) {
    $scope.message = 'hello';
});

app.directive('dynamicHeight', function () {
    return {
        restrict: 'A',
        link: function (scope, elm, attrs) {
            var parent = elm.parent();

            scope.$watch(function () {
                return {
                    height: parent.prop('offsetHeight'),
                    width: parent.prop('offsetWidth')
                };
            }, function (size) {

                // Here you have `size = {height: ... , width: ... }`
                // you can manipulate the element with this data. for example:

                // elm.css('min-width', size.width + 'px');
                // elm.css('min-height', size.height + 'px');

                // -- note that this will make the responsiveness of the ui a bit more challanging 
            }, true);
        }
    };
});

http://jsfiddle.net/f62ccw5a/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接