Cours Web

Réalisation de sites Internet Lausanne


Image dans une fenêtre popup

Pour afficher une grande image quand on clique sur une imagette, placer le code suivant dans l'imagette:

<img onclick="showImage('grande.jpg', 400, 300);" src="petite.jpg" />

Ensuite il faut que la fonction showImage ci-dessous soit accessible de la page (soit en interne, soit en tant que script externe)

Il est aussi intéressant d'appliquer un style cursor: pointer à la balise img de l'imagette pour notifier qu'on peut cliquer dessus.

function showImage(url, width, height)
{
	var max_width = screen.width-100;
	var max_height = screen.height-100;
	var full_view = max_width>=width && max_height>=height;
	var win_width = full_view ? width : Math.min(width, max_width);
	var win_height = full_view ? height : Math.min(height, max_height);
	var win_top = Math.floor((screen.height - win_height - 16)/2);
	var win_left = Math.floor((screen.width - win_width)/2);
	var sb = full_view ? '' : ',scrollbars=yes';
	var wnd = window.open("", "wf2image", "width=" + win_width + ",height=" + win_height + ",left=" + win_left + ",top=" + win_top + sb );
	var doc = wnd.document;
		
	doc.open();
				
	doc.write('<html><head><title></title></head>');
	if(full_view) {
		doc.write('<body style="margin: 0; background-color: #000000; background: url('+url+') no-repeat 0 0;" onBlur="self.close()">'); 
	    doc.write('&nbsp;');
		doc.write('</body></html>');
		doc.close();
		wnd.onmouseup = function(event) {
			var e = event || window.event;
			if(e.button<2) wnd.close();
		}
	}
	else {
		doc.write('<body style="margin: 0; background-color: #000000;" onBlur="self.close()">'); 
		doc.write('<img onclick="window.close();" src="' + url + '" width="' + width + '" height="' + height + '" alt="" border="0">');
		doc.write('</body></html>');
		doc.close();
	}
	wnd.focus();
}