In jquery, the width() method is used to set or return the width of the specified element. The syntax is "element object.width()" or "element object.width (set width)"; when the width is returned When , the returned result is the width of the first matched element.
The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.
width() method sets or returns the width of the selected element.
When this method is used to return the width, it returns the width of the first matching element.
When this method is used to set the width, the width of all matching elements is set.
As shown in the image below, this method does not contain padding, border or margin.
Return width:
$(selector).width()
Set width:
$(selector).width(value)
Use function to set width:
$(selector).width(function(index,currentwidth))
The example is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>123</title> <script src="js/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ alert("div的宽度: " + $("div").width()); }); }); </script> </head> <body> <div style="height:100px;width:300px;padding:10px;margin:3px;border:1px solid blue;background-color:lightblue;"></div><br> <button>显示div的宽度</button> </body> </html>
Output result:
After clicking the button:
Related video tutorial Recommended: jQuery video tutorial
The above is the detailed content of How to use width method in jquery. For more information, please follow other related articles on the PHP Chinese website!