繁体   English   中英

如何在javascript函数中获取当前HTML元素的height和width属性

[英]How to get Current HTML element height and width property in javascript function

我想访问当前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');
}

我无法读取width和height属性。 你有什么建议吗?

您尝试的问题在于,与常规HTML事件属性(如onclickngClass等)不同, 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

使用element.offsetWidth和element.offsetHeight

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

说明

编辑:

为了回应您的评论,请尝试使用:

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;
var width = document.getElementById('<Element's ID>').offsetWidth;
var height= document.getElementById('<Element's ID>').offseHeight;

您需要使用$ 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');

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM