2013-07-16 28 views
7

我想要使用jquery獲取元素的內聯屬性:width: auto。 只要我得到寬度,.width()返回一個px值而不是auto。 這是什麼,我需要一個例子:JQuery - 獲取寬度:自動從內聯樣式

我有一個img用設置好的這個內嵌樣式:

<img id='image' style='position: absolute; height: 200px; width: auto; top: 25px; left: 50px;' src='http://tinyurl.com/k8ef66b'/> 

我需要來包裝圖像中的a,使圖像點擊。我也需要得到的影像風格,並將其移動到錨標記:

//--- get height, width and entire style 
var imgHeight = $("#image").height(); 
var imgWidth = $("#image").width(); 
var imgStyle = $("#image").attr("style"); 

//---remove inline style from the img 
$("#image").removeAttr("style"); 

//--- create the <a>, add the inline style 
var anch = $("<a href='#'></a>"); 
$(anch).attr("style", imgStyle); 

//--- add back to the img it's width and height 
//--- the problem is here: imgWidth does not contain 'auto' 
$("#image").css({"width" : imgWidth, "height" : imgHeight}); 

//--- wrap the img 
$("#image").wrap(anch); 

這裏的代碼小提琴:http://jsfiddle.net/cBXAz/1/

什麼想法?我怎樣才能使auto超出內聯樣式?我需要給width: auto而不是px值。

在此先感謝,最好的問候

+1

'$( 「#圖像」)的CSS({ 「寬度」: 「自動」}) '??? – Morpheus

+0

當我看小提琴時,我看不到圖像上有'height:auto'。 –

+0

@KevinBowersox我寫的「寬度:汽車」,而不是「高度」 :) – BeNdErR

回答

7
document.getElementById('image').style.width; 

或瞭解更多jQuery的方式:

$("#image")[0].style.width; 
+0

在這種情況下,你會得到實際寬度形象,不'auto' :) – Morpheus

+0

http://jsfiddle.net/JA2ds/如果你改變工作肯定 –

+0

更多jQuery的方式寬度之前使用它是'$(「#圖像」)。寬度()'或'$( 「#圖像」)。CSS( '寬')' – jQuery00