如何确保图像在JQuery插件中加载? [英] How to ensure images are loaded inside a JQuery plugin?
问题描述
在创建需要图片尺寸的JQuery插件时,我发现诸如Chrome之类的webkit浏览器通常会为图片返回0尺寸,因为它们是并行加载的。
我的快速和肮脏的解决方案是包装在 $(window).load()
事件中调用我的插件的代码:
$(document).ready(function(){
$(window).load(function(){
$('。magnifier')。放大镜();
});
});
我该如何去实现这个插件本身?什么是最简洁的方式来检测图像已加载,所以我可以测量其尺寸?
解决方案图像有一个load()事件,所以你可以做一些事情:
$(document).ready(function(){
$(' .magnifier')。magnifier();
});
$ .fn.magnifier = function(){
return this.each(function(){
$(this).find('img')。load(function (){
//当它被加载时做一些图像
});
});
}
您也可以简单地将代码包装在插件本身的window.load中:
$。fn.magnifier = function(){
var that = this;
$(window).load(function(){
that.each(function(){
$(this).find('img')。each(function(){
//图像将在此处加载
});
});
});
返回此;
}
While creating a JQuery plugin that required image dimensions, I discovered that webkit browsers like Chrome often return 0 size for images because they're loaded in parallel.
My quick and dirty solution was to wrap the code that calls my plugin in a $(window).load()
event:
$(document).ready(function() {
$(window).load(function() {
$('.magnifier').magnifier();
});
});
How would I go about implementing this inside the plugin itself? What is the cleanest way to detect that images have loaded so I can measure their dimensions?
Images have a load() event, so you could do something like:
$(document).ready(function() {
$('.magnifier').magnifier();
});
$.fn.magnifier = function() {
return this.each(function() {
$(this).find('img').load(function() {
// do something to image when it is loaded
});
});
}
You could also simply wrap the code around window.load inside the plugin itself:
$.fn.magnifier = function() {
var that = this;
$(window).load(function() {
that.each(function() {
$(this).find('img').each(function() {
// image would be loaded at this point
});
});
});
return this;
}
这篇关于如何确保图像在JQuery插件中加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!