如何在javascript函数中获取当前HTML元素的高度和宽度属性

时间:2015-02-19 06:45:47

标签: javascript html angularjs

我想访问当前html img元素的height和width属性,以根据属性动态应用ngClass

我有这个代码用于html

<div class="cfg-pg-outer-box" ng-repeat="album in album_list">
    <div class="cfg-pg-photo-box">
        <img ng-src="{{album.thumbnail.image_path}}" ng-class="myclass(this)">
    </div>
</div>

我正在使用AngularJS动态应用ngClass

$scope.myclass = function(element) {    
    return (element.width > element.height ? 'landscape' : 'portrait');
}

我无法读取宽度和高度属性。你有什么建议吗?

5 个答案:

答案 0 :(得分:2)

您尝试的问题是,与onclick等常规HTML事件属性不同,ngClass和类似事件具有不同的调用上下文。准确地说this指向当前范围对象。

在您的情况下,您应该编写一个自定义指令来读取/操作DOM元素。例如,简单指令可能如下所示:

app.directive('dimentionClass', function() {
    return {
        link: function(scope, element) {
            var img = element[0];
            img.onload = function() {
                img.className = img.width > img.height ? 'landscape' : 'portrait';
            }
        }
    };
});

你会像这样使用它:

<img ng-src="{{album.thumbnail.image_path}}" dimention-class />

演示: http://plnkr.co/edit/GtklqTUvtbFxb6AFuz4S?p=preview

答案 1 :(得分:1)

使用element.offsetWidth和element.offsetHeight

答案 2 :(得分:1)

var height = document.body.clientHeight;
var width = document.body.clientWidth;

Explanation

修改

在回复您的评论时,请尝试使用:

var element = document.getElementById("elementId");

var height = element.style.height;
var width =  element.style.width;

<强> EDIT2:

您可能还想尝试:

document.getElementById(id_attribute_value).offsetHeight;

和/或

document.getElementById(id_attribute_value).clientHeight;

答案 3 :(得分:1)

var width = document.getElementById('<Element's ID>').offsetWidth;
var height= document.getElementById('<Element's ID>').offseHeight;

答案 4 :(得分:1)

您需要使用$ scope。$ apply,否则在非Angular事件处理程序中对$ scope的任何更改都将无法正确处理:

$ scope.myclass = function(element){

$scope.image.width = img.width;
$scope.image.height = img.height;
$scope.image.path = $scope.imageurl;
$scope.$apply();

   return (this.width > this.height ? 'landscape' : 'portrait');

}