我需要以实际大小显示图像,即使它比其容器大。我尝试了使用 Image 变量的技巧和捕获负载大小 https://stackoverflow.com/a/7686392/196451像这样的东西:
HTML:
<div ng-controller="MyCtrl">
<input ng-model="imageurl" type="url" />
<button ng-click="loadimage()" type="button">Load Image</button>
<img ng-src="{{image.path}}"
style="width: {{image.width}}px; height: {{image.height}}px" />
</div>
JavaScript:
.controller("MyCtrl", ["$scope", function ($scope) {
$scope.image = {
path: "",
width: 0,
height: 0
}
$scope.loadimage = function () {
var img = new Image();
img.onload = function () {
$scope.image.width = img.width;
$scope.image.height = img.height;
$scope.image.path = $scope.imageurl;
}
img.src = $scope.imageurl;
}
}]);
该脚本可以工作,但只有在图像很大的情况下单击按钮几次后才能工作。
我应该怎么做才能使其一键运行?
还有比这更好的方法来发现图像大小吗?
你需要使用$scope.$apply http://docs.angularjs.org/api/ng.%24rootScope.Scope#%24apply,否则任何更改$scope
在非 Angular 事件处理程序中创建的事件将无法正确处理:
img.onload = function () {
$scope.$apply(function() {
$scope.image.width = img.width;
$scope.image.height = img.height;
$scope.image.path = $scope.imageurl;
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)