我需要在加载后使用JavaScript定位/调整图像大小。为了保持纵横比不变,我必须知道图像的宽度/高度。我可以使用该.load
事件,但这触发得太晚了,使重新定位可见。相反,我使用以下技术。
var interval = setInterval(function(){
if ($('img').height()) { //This means we have got height.
//Code that uses $('img').height().
clearInterval(interval);
}
},10);
这可以确保代码在我有图像的宽度/高度信息时以及在它完全加载之前执行。
但是,现在,我需要为一堆图像(特别是在 jQuery 插件中)执行此操作,问题似乎是第一次clearInterval
调用清除了所有间隔,除了第一个之外的所有间隔都img
保持不变。
我尝试将$(this)
jQuery 对象中的间隔 id 保存为属性($(this).interval = setInterval( ...
和 data $(this).data("interval", setInterval( ...
。
我还尝试先将 id 保存在变量中,然后将其分配给调用$(this).data("interval",interval)
的右括号之后setInterval
。
这样做的正确方法是什么,以便每个间隔都清除自己并且只清除自己?
我的代码的完整列表如下
(function($){
$.fn.extend({
centerInParent: function(options) {
var defaults = {
mode: "fill", //Fill or fit (not implemented)
padding: 100
}
var options = $.extend(defaults, options);
return this.each(function() {
var o = options;
$t = $(this)
$p = $t.parent();
var interval = setInterval(function(){
$t.css({position:"absolute", width:"", height:""})
if ($t.height()){
parentRatio = $p.innerWidth()/$p.innerHeight();
thisRatio = $t.innerWidth()/$t.innerHeight();
if (thisRatio > parentRatio) var newWidth = $p.innerWidth() - o.padding; else var newWidth = ($p.innerHeight() - o.padding)*thisRatio;
var newHeight = newWidth/thisRatio
$t.css({
width: newWidth,
height:newHeight,
marginTop: ($p.innerHeight() - newHeight)/2,
marginLeft: ($p.innerWidth() - newWidth)/2
})
clearInterval($t.data("interval"));
}
}, 10)
$t.data("interval",interval)
});
}
});
})(jQuery);