wtkd

AdaptImage.JS

Sep 25th, 2012
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2.  
  3. // Função adaptImage()
  4. // Parâmetros: targetimg (objeto jquery com elementos selecionados)
  5. function adaptImage(targetimg) {
  6.     var wheight = $(window).height(); // altura da janela do navegador
  7.     var wwidth = $(window).width(); // largura da janela do navegador
  8.    
  9.     // removemos os atributos de largura e altura da imagem
  10.     targetimg.removeAttr("width")
  11.              .removeAttr("height")
  12.              .css({ width: "", height: "" }); // removemos possíveis regras css também
  13.    
  14.     var imgwidth = targetimg.width(); // largura da imagem
  15.     var imgheight = targetimg.height(); // altura da imagem
  16.    
  17.     var destwidth = wwidth; // largura que a imagem deve ter
  18.     var destheight = wheight; // altura que a imagem deve ter
  19.    
  20.     // aqui vamos determinar o tamanho final da imagem
  21.     if(imgheight < wheight) {
  22.         // se a altura da imagem for menor que a altura da tela, fazemos um cálculo
  23.         // para redefinir a largura da imagem para bater com a altura que queremos
  24.         destwidth = (imgwidth * wheight)/imgheight;
  25.        
  26.         $('#fundo img').height(destheight);
  27.         $('#fundo img').width(destwidth);
  28.     }
  29.    
  30.     // aqui utilizamos um cálculo simples para determinar o posicionamento da imagem
  31.     // para que a mesma fique no meio da tela
  32.     // posição = dimensão da imagem/2 - dimensão da tela/2
  33.     destheight = $('#fundo img').height();
  34.     var posy = (destheight/2 - wheight/2);
  35.     var posx = (destwidth/2 - wwidth/2);
  36.    
  37.     //se o cálculo das posições der resultado positivo, trocamos para negativo
  38.     if(posy > 0) {
  39.         posy *= -1;
  40.     }
  41.     if(posx > 0) {
  42.         posx *= -1;
  43.     }
  44.    
  45.     // colocamos através da função css() do jquery o posicionamento da imagem
  46.     $('#fundo').css({'top': posy + 'px', 'left': posx + 'px'});
  47. }
  48.  
  49. //quando a janela for redimensionada, adaptamos a imagem
  50. $(window).resize(function() {
  51.     adaptImage($('#fundo img'));
  52. });
  53.  
  54. //quando a página carregar, fazemos o mesmo
  55. $(window).load(function() {
  56.     $(window).resize();
  57. });
Advertisement
Add Comment
Please, Sign In to add comment