.width()

要素の横幅を計算します。

width( ) 1.0追加

戻り値:Integer

要素の横幅を算出します。 .css('width')と.width()の違いは、後者である.width()はpxを含まない数値を返してくれます。(例:400) 一方、.css('width')はpx含む文字列で値を返します。(例:400px) 通常、計算を行う場合は、width()が使用されます。

width

width( value ) 1.0追加

戻り値:jQuery

要素のCSSのwidthに指定した値を設定します。

引数 説明
value px単位で設定したい横幅を指定します。

width( function(index, width) ) 1.4.1追加

戻り値:jQuery

要素のCSSのwidthに指定した関数の戻り値を設定します。

引数 説明
function(index, width) px単位で設定したい横幅を戻り値で返す関数を指定します。 関数に渡される引数は下記の通りです。
index
要素の番号です。
width
変更前に設定されている要素の横幅です。

デモ

下記はPタグ、Document、iFrame内のWindowの横幅を取得するデモです。 iFrame内のWindowとDocumentの横幅の関係を確認してください。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <style>
  5. body { background:yellow; }
  6. button { font-size:12px; margin:2px; }
  7. p { width:150px; border:1px red solid; }
  8. div { color:red; font-weight:bold; }
  9. </style>
  10. <script src="http://code.jquery.com/jquery-latest.js"></script>
  11. </head>
  12. <body>
  13. <button id="getp">Pタグ領域の横幅</button>
  14. <button id="getd">Document領域の横幅</button>
  15. <button id="getw">Window領域の横幅</button>
  16. <div>&nbsp;</div>
  17. <p>
  18. テスト用Pタグ領域です。
  19. </p>
  20. <script>
  21. function showWidth(ele, w) {
  22. $("div").text(ele + "の横幅は" + w + "pxです。");
  23. }
  24. $("#getp").click(function () {
  25. showWidth("Pタグ領域", $("p").width());
  26. });
  27. $("#getd").click(function () {
  28. showWidth("Document領域", $(document).width());
  29. });
  30. $("#getw").click(function () {
  31. showWidth("Window領域", $(window).width());
  32. });
  33. </script>
  34. </body>
  35. </html>

DIV領域の横幅を変更後、色を変更するデモです。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <style>
  5. div { width: 70px; height: 50px; float:left; margin: 5px;
  6. background: red; cursor: pointer; }
  7. .mod { background: blue; cursor: default; }
  8. </style>
  9. <script src="http://code.jquery.com/jquery-latest.js"></script>
  10. </head>
  11. <body>
  12. <div>d</div>
  13. <div>d</div>
  14. <div>d</div>
  15. <div>d</div>
  16. <div>d</div>
  17. <script>
  18. (function() {
  19. var modWidth = 50;
  20. $("div").one('click', function () {
  21. $(this).width(modWidth).addClass("mod");
  22. modWidth -= 8;
  23. });
  24. })();
  25. </script>
  26. </body>
  27. </html>

 Back to top

© 2010 - 2017 STUDIO KINGDOM