我需要以实际尺寸显示图像,即使它比容器大.我尝试了使用Image变量并在加载时捕获大小的技巧,如下所示:
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>
Run Code Online (Sandbox Code Playgroud)
使用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;
}
}]);
Run Code Online (Sandbox Code Playgroud)
此脚本有效,但只有在图像很大的情况下多次单击按钮后才能使用.
我该怎么做才能让它一键完成?
有没有比这更好的方法来发现图像大小?
您需要使用$scope.$apply,否则$scope将无法正确处理在非Angular事件处理程序中所做的任何更改:
img.onload = function () {
$scope.$apply(function() {
$scope.image.width = img.width;
$scope.image.height = img.height;
$scope.image.path = $scope.imageurl;
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38882 次 |
| 最近记录: |