【问题标题】:angularjs how to find img element height and widthangularjs如何找到img元素的高度和宽度
【发布时间】:2014-01-03 08:09:16
【问题描述】:

您好,我正在尝试查找图像元素的高度和宽度以调整其大小。但是每次我使用 elem.height() 或 elem.width() 我得到 0?

html

<div>
    <img data-ng-src="{{photosrc}}" lightbox-resize-image>
</div>

directive.js

.directive('lightboxResizeImage', function() {
return {
    restrict: 'A',
    link: function(scope, elem, attrs) {

        console.log(elem.parent().width()); //==equals 575
        console.log(elem.width()); //this always equals 0

  }
  });

【问题讨论】:

  • 确保先加载图片。
  • elem.on('load', function(){console.log($(this).width())})
  • 我建议只在确保它没有宽度之后才执行上述操作。缓存的图像可能已经触发了该事件。

标签: javascript jquery css angularjs angularjs-directive


【解决方案1】:

见下面的代码:

.directive('lightboxResizeImage', function() {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
             console.log(elem.parent().width()); // =575
             console.log(elem[0].offsetHeight);
        }
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 2019-02-03
    相关资源
    最近更新 更多