在 jQuery 中, 可以通过使用 height()/width(),innerHeight()/innerWidth()和 outerHeight()/outerWidth()来设置元素的宽高值, 进而操作元素的尺寸.
在 CSS 中, 宽高有三种表示, 分别是 content-box,padding-box 和 border-box 里的三种宽高. 可以分别对应于 jQuery 中 height()/width(),innerHeight()/innerWidth()和 outerHeight()/outerWidth().
1,height(value)/width(value)
当 height()/width()方法中包含一个参数时, 可以设置宽高值. 这个参数可以是一个正整数代表的像素数, 或是整数和一个可选的附加单位(默认是 px)
- <div id="test" style="background-color:pink">测试内容</div>
- <button id="btn">设置宽高</button>
- <script src="http://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
- <script>
- $('#btn').click(function(){
- $('#test').height(30).width(100);
- })
- </script>
效果图:
height(function(index,currentHeight))/width(function(index,currentWidth))
height()/width()方法也可以以一个函数作为参数, 该函数接受两个参数, index 参数表示元素在集合中的位置, currentHeight/currentWidth 参数表示原来的宽高. 在这个函数中, this 指向元素集合中的当前元素, 最终返回设置的宽高
- <button id="btn">设置宽高</button>
- <div>1</div>
- <div>2</div>
- <div>3</div>
- <div>4</div>
- <div>5</div>
- <script src="http://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
- <script>
- $("#btn").click(function(){
- $('div').height(30).CSS('background-color','orange').width(function(index,currentWidth){
- return currentWidth*(index+1)/10
- })
- })
- </script>
2,innerHeight()/innerWidth()
客户区宽高指设置宽高加上 padding 值. 在 JavaScript 中, 客户区宽高用 clientWidth/clientHeight 表示. 而在 jQuery 中, 用 innerHeight()和 innerWidth()方法表示
innerHeight()/innerWidth()方法不适用于 Windows 和 document 对象, 可以使用 height()/width()代替
得到的是内容部分大小 + padding 的大小.
设置时 padding 固定不变, 内容部分自动适应变化.
- <style>
- div {
- width: 500px;
- height: 500px;
- padding: 10px;
- border: 10px solid;
- }
- </style>
- <body>
- <div></div>
- <script src="lib/jquery-1.12.4.js"></script>
- <script>
- var w = $('div').innerwidth(); // 返回的是一个 number
- console.log(w); //520.width+padding
- $('div').innerwidth(300); //div 设置为 300-20=280px,padding 占有 20px
- </script>
- </body>
- 3,outerWidth()/outerHeight()
outerWidth()/outerHeight()方法用来获取元素集合中第一个元素的当前计算宽高值, 包括 padding,border 和选择性的 margin. 返回一个整数 (不包含 px) 表示的值
当参数为 false 或无参数时, 表示不包括 margin, 否则包括 margin
[注意]如果在一个空集合上调用该方法, 则会返回 null
outerWidth()/outerHeight()方法不适用于 Windows 和 document 对象, 可以使用 height()/width()代替
得到的是内容部分大小 + padding + border 的大小.
设置时 padding 和边框 border 固定不变, 内容部分自动适应变化.
- <style>
- div {
- width: 500px;
- height: 500px;
- padding: 10px;
- border: 10px solid;
- }
- </style>
- <body>
- <div></div>
- <script src="lib/jquery-1.12.4.js"></script>
- <script>
- var w = $('div').outerwidth(); // 返回的是一个 number
- console.log(w); //540.width+padding+border
- //div 设置为 300-20-20=260px,padding 占有 20px,border 占有 20px
- $('div').outerwidth(300);
- </script>
- </body>
更多 web 前端开发 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/qa/jquery/16689.html