【发布时间】:2018-11-19 02:13:51
【问题描述】:
我有一个包含图像的 div。现在基于图像的 naturalWidth/naturalHeight 和 offsetwidth/offsetHeight 我正在运行一个函数并进行一些计算以在 div 顶部显示一个绝对层。现在我是使用下面的代码
angular.element(document).ready(function () {
var actual_width = document.getElementById("image_id").naturalWidth;
var actual_height = document.getElementById("image_id").naturalHeight;
var width = document.getElementById("image_id").offsetWidth;
var height = document.getElementById("image_id").offsetHeight;}) //my calculation })
图像数据来自 api。现在问题是有时 naturalWidth 显示未定义,即使我将它放在文档就绪函数中。
1.内容加载或更改后如何运行该函数(我再次调用api而不刷新获取新数据)
2.如何为 div 的每个宽度和高度变化运行相同的函数(当我响应时)。
我正在开发一个 angularjs(angular 1.x) 应用程序
调用api的代码
$http({
method: 'GET',
url: 'some url' + $scope.cursor
}).then(function successCallback(response) {//i get
$scope.formItems = [response.data[0]];
}
在html中
<div class="image-wrapper" ng-repeat="item in formItems">
<div style="{{style1}}" class="img-src relative">
<img ng-src="{{item['img_url']}}" alt="Source" class="main-image" id="image_id">
<!-- below section should get some style based on the image width and height,so i need some something like a funciton which calls everytime page is loaded or if the image changes or window resize -->
<div class="top-section" id="image-top-box-id"></div>
<div class="bottom-section" id="image-bottom-box-id"></div>
</div>
</div>
【问题讨论】:
-
应该把它放在一个指令中并使用
image.onload来访问维度 -
能否提供调用api的代码?或者更好的 JSFiddle 或 Plunker
-
@MatteoMeil 我已经编辑了问题中的代码>请立即查看
标签: javascript angularjs