最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - angularjs how to find img element height and width - Stack Overflow

programmeradmin1浏览0评论

Hi I'm trying to find an image element's height and width in order to resize it. However everytime I use elem.height() or elem.width() I get 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

  }
  });

Hi I'm trying to find an image element's height and width in order to resize it. However everytime I use elem.height() or elem.width() I get 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

  }
  });
Share Improve this question asked Dec 16, 2013 at 2:08 user1424508user1424508 3,30113 gold badges42 silver badges67 bronze badges 3
  • 1 Ensure that the image is loaded first. – Kevin B Commented Dec 16, 2013 at 2:09
  • 9 elem.on('load', function(){console.log($(this).width())}) – Arun P Johny Commented Dec 16, 2013 at 2:16
  • 1 i'd suggest only doing the above after ensuring that it doesn't have a width already. a cached image may have already triggered that event. – Kevin B Commented Dec 16, 2013 at 2:16
Add a ment  | 

1 Answer 1

Reset to default 2

See code below:

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

评论列表(0)

  1. 暂无评论