2009-12-02 2 views
16

는이 같은 뭔가 시도 :jquery로 이미지의 "naturalWidth"를 읽을 수있는 방법이 있습니까?

var Height = $(this).naturalHeight; 

그러나 그것은 작동하지 않습니다.

당신이 할 수있는 최선은 폭과 높이를 설정하지 않고 이미지를 숨기고 원래의 이미지로,이 이미지의 이미지 소스를 사용하는 것입니다

+4

'$ (this) [0] .naturalHeight; '하지만 IE9 +를 지원합니다. 브라우저 지원 –

답변

-8
$this.css('height', 'auto'); 
var height = $this.height(); 
+0

고맙습니다. 빠른 답변을 위해 많이 감사합니다. ^^ – ValiL

+8

$ (this) [0] .naturalHeight는 최신 브라우저에서 작동하지만 IE6-IE8에서는 새로운 이미지 요소를 만들고 너비와 높이를 가져와야합니다. 그것의 높이. css를 'auto'로 설정하는 것은 스타일이 가장 높은 특이성을 가질 경우에만 작동하게됩니다 (반드시 필요하지는 않음). 또한 이미지 요소와 부모 요소의 표시가 영향을 미칩니다 (표시 : 조상 요소에 아무 것도 없으면 0을 반환합니다). – Jack

+0

@ Jack +1 플러그인이이 답변보다 훨씬 강력합니다. http://css-tricks.com/snippets/jquery/get-an-images-native-width/ –

1

을 greez 것을 할 수있는 방법이 있습니까. 그런 다음이 숨겨진 이미지의 크기를 계산하십시오.

그렇지 않으면 서버 측의 물리적 치수를 계산하여 페이지의 숨겨진 요소로 전달하고 숨겨진 요소 값에서 크기를 가져올 수 있습니다. 그것은 허용 솔루션처럼 나에게 보이는

// preload the image 
var height, width = ''; 
var img = new Image(); 
var imgSrc = '/path/to/image.jpg'; 

$(img).load(function() { 
    alert('height: ' + img.height); 
    alert('width: ' + img.width); 
    // garbage collect img 
    delete img; 
}).error(function() { 
    // image couldnt be loaded 
    alert('An error occurred and your image could not be loaded. Please try again.'); 
}).attr({ src: imgSrc }); 
3

한 가지 방법은 동적으로 자바 스크립트를 사용하여 이미지의 사본을로드하고 치수를의 얻는 것입니다 . 가끔 jQuery는 약간 도움이되며 길을 벗어나기 위해 말해야합니다. naturalWidth 또는 naturalHeight를 사용하려면 jQuery 객체를 기본 브라우저 요소 참조로 변환하여 이미 존재하는 것을 사용하십시오.

var Height = document.getElementById($(this).attr("id")).naturalHeight; 
7

객체의 모양을 수정 : 이미지의 크기를 얻을 수

+27

단순히'this.naturalHeight'가 아닌가요? – ThiefMaster

+6

ThiefMaster에 동의합니다. 이 대답은 끔찍한 코드입니다. 'this.naturalHeight'는 훨씬 빠르고 콤팩트하며 id가있는 객체뿐만 아니라 모든 객체에서 작동합니다. – jfriend00

+5

이미 jQuery를 사용하고 있다면 $ (this) [0]은 HTMLElement 인스턴스이거나 $ (this) .get (0)입니다. jQuery가이 작업을 수행했기 때문에 getElementById 호출을 반복하는 것보다 낫다. jquery-wrapped 인스턴스 대신 원시 HTMLElement 클래스에서만 액세스 할 수있는 일부 (일반적으로 크로스 브라우저가 아닌) 속성이 있습니다. –

1

var width = $("img", this).css('width', 'auto').width(); 
var height= $("img", this).css('height', 'auto').height(); 

어쨌든 여기

2

에도 큰 이미지 오래된 IE 버전에서 작동하는 jQuery를 함수의 예입니다 기본적으로 naturalWidthnaturalHeight의 계산이다 노력할 것이다.

/* 
* NaturalWith calculation function. It has to be async, because sometimes(e.g. for IE) it needs to wait for already cached image to load. 
* @param onNaturalWidthDefined callback(img) to be notified when naturalWidth is determined. 
*/ 
jQuery.fn.calculateNaturalWidth = function(onNaturalWidthDefined) { 
    var img = this[0]; 
    var naturalWidth = img.naturalWidth; 
    if (naturalWidth) { 
     onNaturalWidthDefined(img); 
    } else { //No naturalWidth attribute in IE<9 - calculate it manually. 
     var newImg = new Image(); 
     newImg.src = img.src; 
     //Wait for image to load 
     if (newImg.complete) { 
      img.naturalWidth = newImg.width; 
      onNaturalWidthDefined(img); 
     } else { 
      $(newImg).load(function() {img.naturalWidth=newImg.width; onNaturalWidthDefined(img)}); 
     } 
    } 
}; 

사용은 간단 HERE

가입일

$(img).calculateNaturalWidth(function(img) { alert(img.naturalWidth)}); 
1

소스 여기서 짧은 jQuery를 (어떤 버전의) 두 가지 방법을 추가 플러그인 : naturalWidth() 및 naturalHeight는(). naturalWidth 및 naturalHeight가 브라우저에서 지원되는지 여부를 결정하기 위해 분기를 사용합니다. 지원되고있는 경우,이 메서드는 naturalWidth 또는 naturalHeight 속성의 getter가됩니다. 지원되지 않는 경우이 메서드는 스타일이 지정되지 않은 이미지 요소를 새로 만들고 해당 요소의 실제 너비와 높이를 반환합니다.

// adds .naturalWidth() and .naturalHeight() methods to jQuery 
    // for retreaving a normalized naturalWidth and naturalHeight. 
    (function($){ 
    var 
    props = ['Width', 'Height'], 
    prop; 

    while (prop = props.pop()) { 
    (function (natural, prop) { 
     $.fn[natural] = (natural in new Image()) ? 
     function() { 
     return this[0][natural]; 
     } : 
     function() { 
     var 
     node = this[0], 
     img, 
     value; 

     if (node.tagName.toLowerCase() === 'img') { 
     img = new Image(); 
     img.src = node.src, 
     value = img[prop]; 
     } 
     return value; 
     }; 
    }('natural' + prop, prop.toLowerCase())); 
    } 
    }(jQuery)); 

    // Example usage: 
    var 
    nWidth = $('img#example').naturalWidth(), 
    nHeight = $('img#example').naturalHeight(); 
39

나는 내가

var width = $(this).get(0).naturalWidth; 
var height = $(this).get(0).naturalHeight; 

또는

var width = $("selector").get(0).naturalWidth; 
var height = $("selector").get(0).naturalHeight; 
사용 JQuery와 객체에

.naturalWidth/.naturalHeight

속성 자바 스크립트 기본을 사용

jQuery 객체가 선택되지 않은 경우.

With get(0) on a jQuery object you can access the associated DOM-element. 기본 DOM 요소에서 네이티브 javascript 코드 (여기 nativ javascript 특성 .naturalWidth에 액세스)

관련 문제