【问题标题】:Angular ng-class depending on image aspectAngular ng-class 取决于图像方面
【发布时间】:2019-08-01 20:49:32
【问题描述】:

如何根据图像纵横比设置 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>

编辑:由于 IE,CSS object-fit 对我不起作用... :(

【问题讨论】:

  • 看起来应该可以了。它不适合你吗?
  • Nop... "img.width" 不是 img 数组的属性...。我想获取图像的宽度和高度,但我不知道如何
  • 哦,哈...明白了。 this answer 有帮助吗?听起来你需要编写一个指令(当你开始想要弄乱 DOM 时,这很标准)。
  • 嘿 Lex,感谢您的快速回答...也许是的,但我在这里迷路了...//check width and height and apply styling to parent here。我是新手,感谢您的帮助!
  • 我也找到了this,但是...不适用于我的图片...可能是因为 ng-repeat?

标签: angularjs image conditional aspect-ratio ng-class


【解决方案1】:

这里的主要问题是在设置 img json 对象的宽度/高度属性之前等待图像加载。所以这样的事情会起作用。

重要提示:Scope.apply - 因为您要在非角度上下文中更改范围,即在 jQuery 中,您需要调用 scope.apply 以便发生摘要观察循环并正确设置变量。

Plunker

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);
            });
        });
        }
    };
});

【讨论】:

  • 谢谢琼斯博士。真的我不需要这些属性,它只是一个“草图”。这里重要的是正确应用“宽”或“高”类。 This 是笨蛋。您将看到预期结果的示例。再次感谢您的帮助和时间!
  • 上面更新了解决方案。
  • 琼斯博士,谢谢你,plunker 已经是了!但是在我的应用程序中无法正常工作...这两行有问题scope.$parent.imagen.width = $(element).width();scope.$parent.imagen.height = $(element).height(); 在调试模式下,我没有看到将值$(element).width(); 传递给scope.$parent.imageMeta.width... 在这行之后,@ 987654329@未定义。
  • ...在角度上下文中,什么是解决方案?
  • 我更新了代码以删除 $parent。不是真的需要。由于这在 Plunker 中有效,我认为这个问题已经得到解答。我认为这取决于你从这里拿走它。
【解决方案2】:

经过多次搜索,我找到了一个简单而性感的答案……它是一个名为 object-fit 的 CSS img 元素属性。它可以具有以下值:填充、包含、覆盖、缩放、无。

img {
  object-fit: cover;
}

【讨论】:

    猜你喜欢
    • 2014-05-13
    • 2023-03-27
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多