Angular ng-class 取决于图像纵横比
Angular ng-class depending on image aspect
如何根据图像宽高比设置 ng-class(在 ng-repeat 内)?
类似...
<div ng-repeat="img in images" style="width: 100px; height: 100px;">
<img ng-src="{{img}}" ng-class="{'wide': img.width/img.height > 1, 'tall': img.width/img.height <= 1}" />
</div>
编辑:CSS object-fit 对我不起作用,因为 IE...:(
这里的主要问题是在设置 img json 对象的宽度/高度属性之前等待图像加载。所以这样的事情会起作用。
重要提示:Scope.apply - 因为您正在非 angular 上下文中更改范围,即在 jQuery 中您需要调用 scope.apply 所以摘要-观察周期发生并且变量设置正确。
HTML:
<img ng-src="{{img}}" image-set-aspect ng-class="{'wide': img.width/img.height > 1, 'tall': img.width/img.height <= 1}" />
指令:
app.directive('imageSetAspect', function() {
return {
scope: false,
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('load', function() {
// Use jquery on 'element' to grab image and get dimensions.
scope.$apply(function() {
scope.imageMeta.width = $(element).width();
scope.imageMeta.height = $(element).height();
console.log(scope.$parent.imageMeta);
});
});
}
};
});
经过多次搜索,我找到了一个简单而性感的答案...它是一个名为 object-fit 的 CSS img 元素 属性。它可以有这些值:fill、contain、cover、scale、none.
img {
object-fit: cover;
}
如何根据图像宽高比设置 ng-class(在 ng-repeat 内)?
类似...
<div ng-repeat="img in images" style="width: 100px; height: 100px;">
<img ng-src="{{img}}" ng-class="{'wide': img.width/img.height > 1, 'tall': img.width/img.height <= 1}" />
</div>
编辑:CSS object-fit 对我不起作用,因为 IE...:(
这里的主要问题是在设置 img json 对象的宽度/高度属性之前等待图像加载。所以这样的事情会起作用。
重要提示:Scope.apply - 因为您正在非 angular 上下文中更改范围,即在 jQuery 中您需要调用 scope.apply 所以摘要-观察周期发生并且变量设置正确。
HTML:
<img ng-src="{{img}}" image-set-aspect ng-class="{'wide': img.width/img.height > 1, 'tall': img.width/img.height <= 1}" />
指令:
app.directive('imageSetAspect', function() {
return {
scope: false,
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('load', function() {
// Use jquery on 'element' to grab image and get dimensions.
scope.$apply(function() {
scope.imageMeta.width = $(element).width();
scope.imageMeta.height = $(element).height();
console.log(scope.$parent.imageMeta);
});
});
}
};
});
经过多次搜索,我找到了一个简单而性感的答案...它是一个名为 object-fit 的 CSS img 元素 属性。它可以有这些值:fill、contain、cover、scale、none.
img {
object-fit: cover;
}