2016-11-28 171 views
1

我有圖像標記以下如何從圖像標籤獲取寬度和高度屬性?

<img class="someclass" src="somesrc" width="220" height="165" /> 

的瀏覽器,其原有的寬度和高度,這是480x360

顯示圖像我想要得到的圖像寬度和高度從圖像標籤的屬性即應返回220 and 165

我曾嘗試以下

var img = document.getElementsByClassName('someclass'); 
console.log(img.clientWidth); 
console.log($('.someclass').attr('width')); 

但它返回我undefined

以下代碼返回圖像的實際寬度和高度。這是480

$('.someclass').width(); 

有什麼辦法,它應該返回220 and 165

+1

'img'是'HTMLCollection',而不是元素 – MysterX

+0

'document.getElementsByClassName( 'SomeClass的')[0]'' –

+2

$(」。SomeClass的 ')。ATTR(' 寬度 ')'應當' ve worked fine – adeneo

回答

0

感謝大家的幫助。但我找到了解決辦法。 以下代碼適用於我。

$('img.someclass).load(function(){ 
    var width = $(this).attr('width'); 
    var height = $(this).attr('height'); 
    if(width != 'undefined') { 
    $(this).css('width', width); 
    } 
    if(height != 'undefined') { 
    $(this).css('height', height); 
    } 
}); 
-1
var x = document.createElement("IMG"); 
x.setAttribute("src", "path/here"); 
x.setAttribute("width", "220"); 
x.setAttribute("height", "165"); 
document.getElementById("SomeID").appendChild(x); 

給它一些ID,這應該工作,如果你想使用JS。

0

您需要在返回時獲取單個元素的width屬性而不是nodeList。

嘗試......

var element = document.querySelector('.someclass'); 
console.log(element.getAttribute('width')); //220 
console.log(element.getAttribute('height')); //165 
-1

嘗試

var img = document.getElementsByClassName('someclass')[0]; 
var width = img.width; 
var height = img.height 

,並在情況下,你要設置新的價值只是做:

img.width = yourvalue; 
img.height = yourvalue; 

它工作得很好,所以PLZ不要沒有理由讓人無望地投降

+0

你誤讀了他在屬性值之後的問題,而不是渲染的寬度/高度 – Zinc

相關問題