问题描述
|
我正在编写一个相当复杂的AJAX驱动的菜单,该菜单具有围绕多个层次的动画,允许用户在某个时候导航复杂的树结构,我不得不添加一个功能,该功能可以自动居中(垂直和水平)与每个项目相关的图像菜单树。为了测量图像并相应地定位它们,我必须先将它们写入隐藏的div(\“#tempHolder \”)。一旦它们.load()我就可以获取其尺寸,计算偏移量,然后将图像写入到DOM在适当的位置。
所有这些在符合标准的浏览器中都可以,但是IE7-8似乎只在感觉到时才处理.load()命令。 (主页菜单加载正常,第一次访问子页面会中断菜单,刷新所述页面会再次对其进行修复...等)。由于我在这里阅读了以下建议,我对函数进行了重组以尽早声明.load()声明(http://blog.stchur.com/2008/02/26/ie-quirk-with-onload-event-for-img -elements /),但似乎没有用。我还添加了e.preventDefault,因为有一个stackOverflow线程,该线程说这可能会阻止IE缓存我的加载语句。
这是导致问题的函数:
if (this.imagePath != \"\") {
runImage = function (imagePath,$itemEle) {
var $itemEleA = $itemEle.find(\'a\');
var image = new Image();
//$thisImage = $(image);
$(image).load(function (e) {
//alert(\'image loaded\')
$(image).evenIfHidden(function (element) {
//alert(\'even if hidden\');
////////////console.log($thisImage);
var elementWidth = element.width();
var elementHeight = element.height();
this.imageHeight = elementHeight;
this.imageWidth = elementWidth;
//alert(\'widthoffset = \' + widthOffset + \'imagewidth = \' + imageWidth + \'this.imageWidth = \' + this.imageWidth + \'elementWidth = \' + elementWidth);
var imagePaddingWidth = 230 - imageWidth;
var widthOffset = imagePaddingWidth / 2;
widthOffset = widthOffset + \"px\";
element.css(\"left\",widthOffset);
var imagePaddingHeight = 112 - imageHeight;
if (imagePaddingHeight < 0) {
var heightOffset = imagePaddingHeight;
heightOffset = heightOffset + \"px\";
element.css(\"top\",heightOffset);
}
if (imagePaddingHeight > 0) {
var heightOffset = imagePaddingHeight - 18;
heightOffset = heightOffset + \"px\";
element.css(\"top\",heightOffset);
}
});
$(this).appendTo($itemEleA);
e.preventDefault();
return image;
});
image.src = imagePath;
//var tempvar = $itemEle.find(\'a\');
$(image).appendTo(\"#tempHolder\");
}
this.image = runImage(this.imagePath,$itemEle);
}
由于这是给一个大客户使用的,并且该站点尚未启用,所以我无法显示该站点,但是稍后我将尝试抛出一些屏幕截图。
任何帮助是极大的赞赏。
解决方法
这是一个非常普遍的问题,如果图像已经在缓存中,则某些浏览器(我直接说-IE?)无法在其上触发加载事件。因此,有一种解决方法。
// After this line of your code
image.src = imagePath;
// put this
if (image.complete || image.naturalWidth > 0) { // if image already loaded
$(image).load(); // trigger event manually
}