Javascript 使用angular指令和jqLite选择第一个子图像标记
我有一个循环执行的指令,名为Javascript 使用angular指令和jqLite选择第一个子图像标记,javascript,html,angularjs,angularjs-directive,Javascript,Html,Angularjs,Angularjs Directive,我有一个循环执行的指令,名为waPages 在这个标记中有几个子节点;其中之一是图像标签 模板: <li wa-pages page="page" ng-repeat="page in carousel.pages"></li> <div id="page-{{page.pageindex}}"> <img ng-src="{{page.imageurl}}" on-load /> </div> angular.module(
waPages
在这个标记中有几个子节点;其中之一是图像标签
模板:
<li wa-pages page="page" ng-repeat="page in carousel.pages"></li>
<div id="page-{{page.pageindex}}">
<img ng-src="{{page.imageurl}}" on-load />
</div>
angular.module('carouselApp')
.directive('waPages', function (Pages, Carousel) {
return {
scope: {
page: "="
},
templateUrl: 'views/wa.pages.html',
transclude: true,
require: '^waCarousel',
link: function (scope, el, attrs, ctrl) {
//this wont work obviously
var imageWidth = el[0].find('img:first-child').innerWidth;
}
}
});
更新她的myconsole.log(el[0])代码>
只要扩展我的评论来回答,您就可以在img标签上设置onload
事件。所以一旦图像被加载,抓取它的尺寸。还要注意选择器
从模板中删除ng src并直接在元素上设置它:-
.directive('waPages', function ($window) {
return {
scope: {
page: "="
},
templateUrl: 'wa.pages.html',
transclude: true,
link: function (scope, el, attrs, ctrl) {
var $img = el.find('img')[0]; //get the image
$img.src = scope.page.imageurl; //set the url
$img.onload = function() {
console.log(this.width, this.height); //Get height and width
}
}
}
});
如果您通过css为图像设置了特定的高度和宽度,则加载不同尺寸的图像将无法获取真实尺寸。在这种情况下,您可以从图像的属性(旧浏览器不支持)获取其原始宽度
您还可以创建一个临时图像标记,加载图像src并获取其高度和宽度在图像上注册onload并设置src,或者创建一个临时图像元素,设置相同的src并在加载时计算innerwidth。您的选择器也不正确。请这样使用var imageWidth=$(el).find('img:first').width()代码>我没有使用jquery,只有jqliteI可以将超时设置为30秒,或者直接通过子项选择超时。有几次仍然没有任何innerWidth未定义
link: function (scope, el, attrs, ctrl) {
var $img = el.find('img')[0];
//Just set ng-src itself
//$img.src = scope.page.imageurl;
$img.onload = function() {
console.log(this.naturalWidth, this.naturalHeight);
}
}