2013-04-06 67 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>