如何从jCrop获取height属性

时间:2014-02-13 00:04:21

标签: javascript jquery angularjs angularjs-directive

我有这个使用jQuery的指令。我无法从height

中获取widthmyImage
cmsApp.directive('imgCropped', function() {
  return {
    restrict: 'E',
    replace: true,
    scope: { src:'@', selected:'&' },
    link: function(scope,element, attr) {
      var myImg;
      var clear = function() {
        if (myImg) {
          myImg.next().remove();
          myImg.remove();
          myImg = undefined;
        }
      };
      scope.$watch('src', function(nv) {        
        clear();
        if (nv) {
          element.after('<img />');
          myImg = element.next();  
          myImg.attr('src',nv);
          console.log(myImg[0]);
          console.log(myImg);

          $(myImg).Jcrop({
            trackDocument: true,  
            onSelect: function(x) {              
              scope.$apply(function() {
                scope.selected({cords: x});
              });
            },
            aspectRatio:1
          });
        }
      });

      scope.$on('$destroy', clear);
    }
  };
});

console.log(myImg)返回此内容,减去所有事件侦听器和内容

    [img, ready: function, toString: function, eq: function, push: function, sort: function…]
0: img
height: 259
naturalHeight: 259
naturalWidth: 417
width: 417
x: 0
y: 0
__proto__: HTMLImageElement
length: 1

宽度和高度就在那里。我无法得到它们。

myImg[0].height返回0.

编辑:PLUNKER

以下是尝试console.log myImg的各种属性的“工作”示例

http://plnkr.co/edit/sGIdfi2b8UztEl2DEhf7?p=preview

2 个答案:

答案 0 :(得分:1)

应该可以通过以下方式检索它们:

myImg.naturalHeight
myImg.naturalWidth

更新

根据plunker,问题是你需要在加载图像后访问属性,所以:

$(myImg).load(function(){
    console.log(myImg[0].naturalHeight);
});

正在运作!在这里分叉:http://plnkr.co/edit/DBey1vrD0QSgJhPc3ApX?p=preview

答案 1 :(得分:0)

您需要在 Angular之前加入jQuery 。然后你可以这样做:

console.log(myImg.height());
console.log(myImg.width());

Plunker:http://plnkr.co/edit/ZjciYt4I4VxT8wPQmCTa?p=preview

但是,这里有另一个问题。在设置图像 src 属性后,您正在查询高度和宽度,立即。因此,在较小的图像上,当您第一次查询高度和宽度时,您将获得 0 ,因为图像尚未加载。你可以解决这个问题,通过查询>加载图像后的高度和宽度(收听图像加载事件)。

Plunker:http://plnkr.co/edit/hV2mNvT07qLZFLXHcUuo?p=preview

修改 另外,我没有解释为什么你需要在之前包含jQuery ,抱歉。如果首先包含jQuery,它将使用jQuery,但如果它没有找到它,它将使用 jqLit​​e 。您可以查看http://docs.angularjs.org/api/angular.element上的更多信息,但基本上可以从文档中引用:

  

jqLit​​e仅实现最常用的功能,目标是占用空间非常小

jqLit​​e中不包含

height() width()