2012-03-06 2 views
1

이미지를 뷰포트/창 크기에 맞추어야합니다.뷰포트에 이미지 맞추기

나는 그 일을이 코드를 사용

$(".fittedImg").each(function() { 

     // I want to limit the size, and show a scrollbar on very small viewport 
     height = ($(window).height() < 725) ? 725 : $(window).height(); 
     width = ($(window).width() < 1150) ? 1150 : $(window).width(); 

     var newWidth, newHeight; 
     $(this) 
      .removeAttr("height") 
      .removeAttr("width"); // reset img size 

     // calculate dimension and keep it 
     if (($(this).width()/width) > ($(this).height()/height)) { 
      newHeight = height; 
      newWidth = height/($(this).height()/$(this).width()); 

     } else { 
      newHeight = width/($(this).width()/$(this).height()); 
      newWidth = width; 
     }; 
     $(this).stop(true, false).animate({ 
      "height": newHeight + "px", 
      "width": newWidth + "px" 
     }); 
}); 

은 내가 크기 조정에 전화 기능에 해당 코드를 포장, 및 $ ('fittedImg.') 등의 이벤트에 부하()와 $를. ('.fImg'). 준비().

결과가 매우 이상합니다. Chrome에서는 정상적으로 작동하지만 이미지가 반복적으로 새로 고침 될 때마다 늘어납니다. IE에는 꽤 똑같은 문제가 있습니다. Opera는 결코 실패하지 않으며 사파리는 전혀 계산을 무시합니다.

계산 및/또는 이벤트 호출에 문제가 있습니까?

감사합니다.

답변

3
  1. 포함하는 요소 내부의 이미지를 (적합 할 이미지가 완전히 너비/높이 당신에게 가정

을 계산하기 전에 속성을 제거하지 마십시오 너비/높이

  • 를 추출하기 전에로드되어 있는지 확인합니다 이 경우 window) 여기에 유용한 몇 가지 간단한 계산이 있습니다. 개념은 포함하는 측정 및 이미지 측정에 따라 매우 간단하며 비율을 계산합니다. 그런 다음 원래의 조치를 곱

    $(".fittedImg").load(function(){ 
    
        var imgWidth = this.width, 
         imgHeight = this.height, 
         winWidth = $(window).height(), 
         winHeight = $(window).width(), 
         ratio = Math.min(winWidth/imgWidth, winHeight/imgHeight); 
    
        // if you don’t want it to upscale, use Math.min or Math.max on the ratio 
    
        $(this).stop(true, false).animate({ 
         height: imgHeight*ratio, 
         width: imgWidth*ratio 
        }); 
    }); 
    

    유의하시기 바랍니다 같은 AdBlock을 캔 엉망 이미지에서 추출 된 너비/높이와 같은 일부 확장. imgWidth/imgHeight을 콘솔로 만들고 텍스트를 사용할 수 있는지 확인하기 만하면됩니다.

    코드 삽입 위치에 따라이 이벤트가 추가 될 때 이미 이미지가로드 될 가능성이 있습니다. 이 경우 IMG 요소의 속성이 있는지 확인해야합니다.

    $('fittedImg').each(function() { 
        $(this).load(function() { 
         // the calculations goes here 
        }); 
        if (this.complete) { // check if image is already loaded 
         $(this).trigger('load'); 
        } 
    }); 
    
  • +0

    1. 어떻게해야합니까? load()와 ready()는 충분하지 못하나요? 2. 도움이되지 않습니다. – SRachamim

    +0

    예제를 상용구로 사용하십시오. '.load()'는 너비/높이를 얻기에 충분해야하지만 핸들러에서 값을 콘솔로 확인할 수 있습니다. – David