前端页面开发时,通过jquery有两种方法获取与设置div的宽高:使用尺寸函数或使用css方法。
一、获取宽和高
1.1 尺寸函数:
width() 获取宽度 height() 获取高度
1.2 css方法:
css("width")获取宽度 css("height")获取高度
区别:
尺寸函数返回的值为整型,而css获取的值为带px的字符串
举例:
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache,must-ridate"> <meta http-equiv="expires" content="0"> <script src="./plugins/jquery/jquery.min.js"></script> <style> .box { width: 200px; height: 200px; background-color: grey; } </style> </head> <body> <div class="box"> </div> <input type="button" οnclick="handleClick()" value="获取宽高"> <input type="button" οnclick="handleClick()" value="改变宽高"> </body> <script> function handleClick() { // 1. 使用width(),height()方法来获取宽高,返回的是整形数字 var divw = $('.box').width(); var divh = $('.box').height(); console.log("div宽:" + divw + ";div高:" + divh); // 2.使用css方式获取宽高,返回的带px的字符串 var divw = $('.box').css("width"); var divh = $('.box').css("height"); console.log("div宽:" + divw + ";div高:" + divh); } </script> </html>
以上两种方式,输出的值为:
div宽:200;div高:200 div宽:200px;div高:200px
二、设置宽和高
2.1 尺寸函数:
width(整数值)设置宽度 height(整数值)设置高度
2.2 css方法:
css({"width":"整数值px","height":"整数值px"}) // 使用css设置多个属性时,放在大括号中属性间用逗号分隔 或 css("width","整数值px") // 使用css设置单个属性时,将属性名称与属性值使用逗号分隔(不需要放到大括号中) css("height","整数值px")
区别:
尺寸函数设置的值为整型,而css设置的值为带px的字符串
举例:
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache,must-ridate"> <meta http-equiv="expires" content="0"> <script src="./plugins/jquery/jquery.min.js"></script> <style> .box { width: 200px; height: 200px; background-color: grey; } </style> </head> <body> <div class="box"> </div> <input type="button" οnclick="handleSet1()" value="改变宽高(函数)"> <input type="button" οnclick="handleSet2()" value="改变宽高(CSS)"> </body> <script> function handleSet1() { // 1. 使用width(),height()方法来设置宽高 var divw = $('.box').width(100); var divh = $('.box').height(150); } function handleSet2() { // 2.使用css方式来设置宽高 var divw = $('.box').css("width", "20px"); var divh = $('.box').css("height", "20px"); } </script> </html>