JQuery无法获取动态添加的图片宽度问题解决办法

时间:2024-03-17 14:00:22
 1 $(\'.imgUl li,.v_img\').click(function(){
 2         var _left = 0;
 3         var _top = 0;
 4         $(\'body\').append(\'<div class="pop"><div class="pop_con"><a href="javascript:;" class="img_close"><img src="images/img_close.png"></a><img src="\'+$(this).children(\'.pic-off\').attr(\'rel\')+\'" class="pic_b"/></div></div>\');
 5         var newImg = new Image();
 6         newImg.onload = function(){
 7             _h = newImg.height;
 8             _w = newImg.width;
 9             $(\'.opacityDiv\').show();
10             _left = \'-\'+parseInt(_w)/2+\'px\';
11             _top = \'-\'+parseInt(_h)/2+\'px\';
12             $(\'.pop\').css({\'margin-left\':\'-\'+parseInt(_w)/2+\'px\',\'margin-top\':_top});
13             $(\'.img_close\').click(function(){
14                 $(\'.opacityDiv\').hide();
15                 $(\'.pop\').remove();
16             });
17             }
18             newImg.src = $(this).children(\'.pic-off\').attr(\'rel\');
19     });

注:图片在缓存加载时获取的宽度和高度都为0,所以newImg.onload方法可以将图片加载完成后再获取本身的宽高。此时获取的值均为正确的值。