Javascript-форум (https://javascript.ru/forum/)
-   jQuery (https://javascript.ru/forum/jquery/)
-   -   не могу определить размеры img (https://javascript.ru/forum/jquery/18246-ne-mogu-opredelit-razmery-img.html)

dopelher 23.06.2011 06:06

не могу определить размеры img
 
Добрый день! Подскажите, плз, кто знает.
Почему-то img_width и img_height определяются как 0.
Они определяются правильно только в случае, если задать размеры рисунку в CSS. Хотелось бы знать почему...:help:

$(document).ready(function(){
$('.product-image-large').each(function() {			
var MAX_WIDTH = 120;
var MAX_HEIGHT = 90;
var img_width = $(this).width();
var img_height = $(this).height();
var ratio;
if(img_width<MAX_WIDTH && img_height<MAX_HEIGHT){ratio=1;}
else if(img_width>img_height){	ratio=MAX_WIDTH/img_width;}			
else {ratio=MAX_HEIGHT/img_height;}
img_width=img_width*ratio;
img_height=img_height*ratio;
});
$('.product-image-large').css({'width': img_width, 'height': img_height});
});//

trikadin 23.06.2011 06:32

Потому что ширина/высота картинки определяются (нормально) только после её полной загрузки.

<div id="cont"><div>
<script>
cont= document.getElementById("cont");
img= document.createElement("img");
img.onload=function() {alert(img.offsetWidth+ "x" +img.offsetHeight)}; //после загрузки
img.src= "http://www.naturewallpaper.net/wallpapers/hawaiian_rainbow___id_41280-1400x1050.jpg";
cont.appendChild(img);
alert(img.offsetWidth+ "x" +img.offsetHeight); //до загрузки
</script>

dopelher 23.06.2011 06:44

Спасибо за ответ. напрашивается вопрос - а можно ли решить эту проблему средствами jQuery или поможет только JS.
Спасибо.

trikadin 23.06.2011 07:34

В jquery eсть событие load, нет?

Признаться, не силён в jquery, поэтому не могу сказать точно.

dopelher 23.06.2011 11:05

Большое спасибо!
Действительно через load все работает
$('img.product-image-large').load(function(){
						img_resize();
					});

			function img_resize() {
					$('.product-image-large').each(function() {			
					$(this).width('');
					$(this).height('');
					var MAX_WIDTH = 220;
					var MAX_HEIGHT = 180;
					var img_width = $(this).width();
					var img_height = $(this).height();
					var ratio;
					if(img_width<=MAX_WIDTH && img_height<=MAX_HEIGHT){ratio=1;}
					else if(img_width>img_height){	ratio=MAX_WIDTH/img_width;}			
					else {ratio=MAX_HEIGHT/img_height;}
					//alert(ratio);
					//if (ratio>1){ratio=1;}
					$(this).css("width", img_width*ratio); // Set new width
					$(this).css("height", img_height*ratio);  // Scale height based on
					}); }//img_resize()

killer8080 23.06.2011 12:28

dopelher
не оптимально получается, функци img_resize будет вызываться столько раз, сколько картинок в документе и проделывать одну и ту же работу, может лучше как то так?
$('img.product-image-large').load(function(){
	var MAX_WIDTH = 220;
	var MAX_HEIGHT = 180;
	var img_width = $(this).width();
	var img_height = $(this).height();
	var ratio;
	if(img_width<=MAX_WIDTH && img_height<=MAX_HEIGHT){
		ratio=1;
	}
	else if(img_width>img_height){
		ratio=MAX_WIDTH/img_width;
	}
	else {
		ratio=MAX_HEIGHT/img_height;
	}
	//alert(ratio);
	//if (ratio>1){ratio=1;}
	$(this).css("width", img_width*ratio); // Set new width
	$(this).css("height", img_height*ratio);  // Scale height based on
});

dopelher 23.06.2011 16:26

Да можно и так, у меня просто большая картинка одна, у которой меняется src при наведении на маленькие картинки, поэтому удобней каждый раз пересчитывать пропорции через функцию.


Часовой пояс GMT +3, время: 15:33.