2014-09-21 4 views
0

와 '새로운 높이'로 이미지 크기를 조정 I 다음과 같습니다전환 배경 이미지는 jQuery를

HTML :

<div id="section-one" class="section"> 
    <img id="section-one-img" style="width: 100%;" src="http://176.67.174.179/ukcctvinstallations.co.uk/wp-content/uploads/2014/09/section-one-pointers.jpg" /> 
    <div id="section-one-headline"> 
    <h1 class="main-headline"><span class="site-colour border-box">Your local CCTV Company</span> <br /><p class="headline-desc">with over 80 installation teams NATIONWIDE</span></h1> 
    </div> 
</div> 

jQuery를 :

jQuery(document).ready(function() { 
    if (jQuery(window).width() < 880) { 
    jQuery('#section-one-img').attr("src", 'http://176.67.174.179/ukcctvinstallations.co.uk/wp-content/uploads/2014/09/section-one-880px.jpg'); 
    } 
    var imgHeight = jQuery('#section-one-img').height(); 
    jQuery('#section-one-img').height(imgHeight); 
}); 

올바른 새로운 이미지를로드하지만 화면 크기가 < 880이면 이미지의 새 높이가 설정되지 않습니다 (이미지의 아래쪽 부분이 잘립니다).

문제를 해결하기 위해 내 코드에 문제가 있습니까?

Fistly :

+0

새 이미지의 높이는 어떻게되어야합니까? 그것은 항상 100 % 너비와 비율로 유지되어야합니까? –

답변

1

당신은 src 변경 직후 이미지 load() function을 사용해야합니다. 새 이미지가있는 요소를 만들어서 (DOM) 치수를 계산해야합니다. 이러한 이유로

구현

jQuery(document).ready(function() { 
    if (jQuery(window).width() < 880) { 
     var img = 'http://176.67.174.179/ukcctvinstallations.co.uk/wp-content/uploads/2014/09/section-one-880px.jpg';   

     var pic_real_width, pic_real_height; 
     $("<img/>") // Make in memory copy of image to avoid css issues 
      .attr("src", img) 
      .load(function() { 
       pic_real_width = this.width; // Note: $(this).width() will not 
       pic_real_height = this.height; // work for in memory images. 
       /*alert(pic_real_width); 
       alert(pic_real_height);*/ 
      });  
    jQuery('#section-one-img').attr("src", 'http://176.67.174.179/ukcctvinstallations.co.uk/wp-content/uploads/2014/09/section-one-880px.jpg'); 
      jQuery('#section-one-img').height(pic_real_height); 
    } 
}); 

는 희망이 도움에 대한 jsfiddle.net/csdtesting/81r4ktj4/1/에 살펴 보자 : 그럼 우리는 그들을 조정할 수 있습니다!

JS :

+0

여전히 정확히 일치합니까? – nsilva

+0

나는 그것이 어떻게 든 새로운 이미지와 반대로 원래 이미지의 이미지의 높이를 취하는 것 같다고 생각한다. – nsilva

+0

이것은 하나 시도해 본다! –

0

대신 모든 고정 크기를 설정하는 이유는 CSS가 높이를 처리하지

jQuery(document).ready(function() { 
    if (jQuery(window).width() < 880) { 
    jQuery('#section-one-img').attr("src", 'http://176.67.174.179/ukcctvinstallations.co.uk/wp-content/uploads/2014/09/section-one-880px.jpg'); 
    } 
    // removed height setting here 
}); 

CSS :

img { 
    height: auto; 
} 

jsFiddle : http://jsfiddle.net/6cktLr4h/

그러나 jus를 사용하여 다른 이미지를 표시하거나 숨길 수있는 경우 jQuery를 사용하는 이유는 무엇입니까? 미디어 쿼리를 사용하는 CSS? See this answer