我有一个div包含一个image.Now基于我正在运行一个函数的图像的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。现在问题一直是自然宽度显示未定义,即使我把它放在文档就绪函数中。
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]];
}
in 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>
答案 0 :(得分:0)
如果您的图片来自API,您应该在从服务器获得响应后获得宽度和高度;你应该做这样的事情:
angular.element(document).ready(function () {
$http({
method: 'GET',
url: 'some url' + $scope.cursor
}).then(function successCallback(response) {//i get
$scope.formItems = [response.data[0]];
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
})
})
我建议您使用$document
代替angular.element(document)
。阅读docs here。
如果您想在调整窗口大小时获得宽度和高度,则应使用angular.element($window).bind('resize')
。查看this question
答案 1 :(得分:0)
问题在于,即使我在获取api数据后调用naturalWidth,naturalHeight,图像也可能没有加载到dom中,因此显示未定义。
一个方法是在达到api数据后调用一个函数。我在我的函数中传递了图像的url,并且在函数内部我使用了image.onload函数。在onload函数中我可以检查document.getElementById(“ image_id“)。naturalWidth / naturalHeight / whatever。因此它不会抛出未定义的错误。