当调用.width(value)
方法的时候,这个“value”参数可以是一个字符串(数字加单位)或者是一个数字。如果这个“value”参数只提供一个数字,jQuery会自动加上单位px。如果只提供一个字符串,任何有效的CSS尺寸都可以为宽度赋值(就像100px, 50%, 或者 auto)。注意在现代浏览器中,CSS宽度属性不包含padding, border, 或者 margin。除非box-sizing CSS属性被使用。
如果没有给定明确的单位(像'em' 或者 '%'),那么默认情况下“px”会被直接添加上去(也理解为“px”是默认单位)。
注意.width('value')
设置的容器宽度是根据CSS box-sizing属性来定的, 将这个属性值改成border-box将造成这个函数改变成获取这个容器的outerWidth替换原来的内容宽度。
总的来说设值要比取值简单多了,可以直接用style这个接口直接操作,直接注意的就是单位的转化数字需要加上px,还有box-sizing的处理。
<!doctype html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"/> <script src="http://code.jquery.com/jquery-latest.js"></script> <title>jQuery.width</title> <style type="text/css"> div{ width: 100px; height: 100px; } </style> </head> <body> <div style="background:red;border:20px solid #ccc;">DIV</div> <button id="test1">设值</button> <ul></ul> <script type="text/javascript"> var div = document.querySelectorAll('div')[0] $('#test1').click(function(){ show('之前'+ $(div).width()) div.style['width'] = '500px' show('之后'+ div.style['width']) }) function show(data){ $('ul').append('<li>'+ data +'</li>') } </script> </body> </html>