【发布时间】:2015-05-26 14:32:08
【问题描述】:
我需要通过 javascript 检查图像的尺寸(图像尚未在任何地方附加到 DOM),并通过图像上的 load() 事件来完成。
下面的变量 IMAGE 包含一个有效的图像 url。 下面的变量 SELF 包含对插件 THIS 的引用。
问题是在加载事件中我无法访问我的 jQuery 插件的变量。在加载事件之外,我无权访问该事件检查的图像尺寸。
给我尺寸,但不能访问插件范围
//Find dimensions of image
var imageTest = new Image(), iWidth, iHeight;
// just in case it is not already loaded
$(imageTest).load(function () {
iWidth = imageTest.width;
iHeight = imageTest.height;
alert(iWidth+' x '+iHeight);
alert(self.data('overlayTypePreview'));
});
imageTest.src = image;
允许我访问插件范围,但不能访问图像尺寸:
//Find dimensions of image
var imageTest = new Image(), iWidth, iHeight;
// just in case it is not already loaded
$(imageTest).load(function () {
iWidth = imageTest.width;
iHeight = imageTest.height;
});
imageTest.src = image;
alert( self.data('overlayTypePreview') ); // <-- gives me the correct data, string 'mainOverlay'
alert(iWidth+' x '+iHeight); // <-- gives me 'undefined x undefined'
我还尝试了通过窗口的丑陋黑客解决方案,但这对我也不起作用,可能是因为代码应该在加载事件之前触发警报?
//Find dimensions of image
var imageTest = new Image(), iWidth, iHeight;
// just in case it is not already loaded
$(imageTest).load(function () {
window.iWidth = imageTest.width;
window.iHeight = imageTest.height;
});
imageTest.src = image;
alert(window.iWidth+' x '+window.iHeight);
我想我可以建立一个由 3 个函数组成的系统,将线程相互传递,但是从加载事件中无法调用我的 jquery-plugin 实例,对吧? (看到我不知道用户会将插件实例化为什么,否则我可以硬编码实例名称,如果我想要一个更丑陋的解决方案)。
我想我可以从插件内部设置某种超时 ping:ing 图像,而不是使用 load() 事件,但我认为可能有一种我还没有想到的更聪明的方法。 ..
【问题讨论】:
-
什么是“插件范围”?你在说你插件的
this吗? -
是的,我将 this.data('variable') 用于大多数插件变量(以及函数)。
-
在加载函数之外,保存引用:
var self = this;。然后,在负载内部,您可以执行self.imgW = this.width。该值将保存在您的插件中。请记住load是异步的。 -
这几乎等同于我在上面发布的 window.iWidth 选项(尽管您的版本更干净一些),并且效果也很差,这意味着我仍然需要某种 ping:ing查看变量何时实际填充,因为它像您说的那样是异步的。所以不幸的是它并没有解决问题。
-
您可以编辑插件的代码以满足您的需求,并添加您的 load() 内容...?
标签: javascript jquery image jquery-plugins dimensions