2013-04-06 63 views
0

如何動態更改圖片的相對百分比寬度?更改圖片相對寬度

<div style="width: 350px; background-color: #DDDDDD"> 
    <img id="gradient" src="img.png" style="width: 74.074%;"></img> 
</div> 

我一直沒能得到使用attr()或點與jQuery寬度:

<input type="submit" value="button" /> 

<script>                  
$(function() { 
    $("input[type=submit], a, button") 
    .button() 
    .click(function(event) { 
    $("#gradiant").width; 
    }); 
}); 
</script> 
+0

jQuery將得到寬度總是'PX'(代替%),但有點數學應該可以幫助您:!'IMGW * 100/parentW =%' – 2013-04-06 17:07:06

回答

0

用途:

$("#gradiant").width(); 

width()

Get the current computed width for the first element in the set of matched elements or set the width of every matched element. Or:

$("#gradiant").outerWidth(); 

Outerwidth()

Get the current computed width for the first element in the set of matched elements, including padding and border.

您還可以傳遞一個布爾該方法.outerWidth(true),包括(第一)元件的margin在返回的寬度。

順便說一下,我無法找到任何參照button()方法在jQuery API和搜索只返回:button選擇,使用不存在的方法result in an error(檢查控制檯)。

參考文獻:

+0

nether'alert($(「#gradiant」)。width());'也不'alert($(「#gradiant」)。outerWidth());' – 2013-04-06 16:59:51

+0

您是否注意到我提到過的部分沒有'button()'方法?因爲如果你看看控制檯,你會看到一個錯誤:['Uncaught TypeError:Object [object Object] has no method'button''](http://jsfiddle.net/davidThomas/EZCjb/)。一旦該方法被刪除,並且打字錯誤('gradient' /'gradiant')被固定,它就可以與['width()']一起工作(http://jsfiddle.net/davidThomas/EZCjb/1/),[ outerWidth()'](http://jsfiddle.net/davidThomas/EZCjb/2/)*和* ['outerWidth(true)'](http://jsfiddle.net/davidThomas/EZCjb/3/)。 – 2013-04-06 17:03:22

+1

不是.jQuery UI的.button部分?也許這會導致寬度命令的一些問題。 @Philippe:嘗試分解它,在$(「gradiant」)上做一個console.log並從那裏開始工作。 – Zyphrax 2013-04-06 17:15:57

0

gradiAnt = gradient
<img></img> = <img />

<div style="width: 350px; background-color: #DDDDDD"> 
    <img id="gradient" src="img.png" style="width: 74.074%;" /> 
</div> 
<input type="submit" value="button" /> 

<script>                  
$(function() { 
    $("input[type=submit]").click(function() { 
    var imgW = $("#gradient").width(); // in PX (Number) 
    var parentW= $("#gradient").closest('div').width(); 
    var percent= imgW*100/parentW; 

    alert(imgW +' '+ parentW +' '+ percent +'%'); 

    }); 
}); 
</script>