.innerWidth()【要素の幅(内側) 取得・設定】

メモ

  • 共通:要素の幅(内側) 取得・設定
  • 要素の幅(内側) 取得
    • 該当要素の先頭が対象
      該当要素が無い場合、undefined (jQuery 3.0 より前:null)
    • 数値で取得  ( .css( "height" )String【文字列】 で取得 例:"100px")
    • 小数が返却される可能性あり
    • ユーザがページをズームしている場合、不正確 (尚、ブラウザはこの状態の検出 API は非公開)
    • 要素またはその親要素が非表示の場合、不正確 (jQuery は一時的に表示して取得するが、機能削除される可能性あり)
  • 要素の幅(内側) 設定
    • 該当要素の全てが対象
    • 数値設定の場合、ピクセル単位 (px)

構文

説明構文戻り値
要素の幅(内側) 取得 .innerWidth() 1.2.6
Number
要素の幅(内側) 設定 .innerWidth( value ) 1.8.0

String  | Number value:単位付きの文字列等 ("100px"・"50%"・"auto") または 数値(px単位)
jQuery
.innerWidth( function ) 1.8.0

function
引数説明
Integer indexインデックス位置
Number width元の幅
戻り値説明
String
Number
設定値
単位付きの文字列等 ("100px"・"50%"・"auto") または 数値(px単位)
jQuery

関連

<style>
.box {
  width: 50px;
  height: 100px;
  margin: 10px 20px 30px 40px;
  border: 3px red solid;
  padding: 5px 10px 15px 20px;

  float: left;
  text-align: center;
  color: white;
  background-color:blue;
}

#output { border:1px black solid; padding:1px 5px; }
.color1 { color: red; font-weight:bold; }
</style>

<div style="height:200px;">
<div id="id1" class="box">#id1</div>
<div id="id2" class="box">#id2</div>
<div id="id3" class="box change">#id3<br>class change</div>
<div id="id4" class="box change">#id4<br>class change</div>
</div>

<p id="output"></p>

<script>
var SPAN_S = "<span class='color1'>";
var SPAN_E = "</span>";
var BR = "<br>";

function outsub(msg, val1, val2) {
  var out = msg + " : " + val1 + " / " + val2;
  if (val1 !== val2) {
    out = SPAN_S + out + SPAN_E;
  }
  $("#output").append(BR + out);
}

function output(idA, idB) {
  $("#output").append(BR + "id = " + idA + " / " + idB);
  outsub("height()", $(idA).height(), $(idB).height());
  outsub("width()", $(idA).width(), $(idB).width());
  outsub("innerHeight()", $(idA).innerHeight(), $(idB).innerHeight());
  outsub("innerWidth()", $(idA).innerWidth(), $(idB).innerWidth());
  outsub("outerHeight()", $(idA).outerHeight(), $(idB).outerHeight());
  outsub("outerHeight(true)", $(idA).outerHeight(true), $(idB).outerHeight(true));
  outsub("outerWidth()", $(idA).outerWidth(), $(idB).outerWidth());
  outsub("outerWidth(true)", $(idA).outerWidth(true), $(idB).outerWidth(true));
  $("#output").append(BR);
}

function funcChange(index, width) {
  var newWidth = width + (index + 1) * 10;
  $("#output").append(BR + SPAN_S + "function [" + index + "] " + width + " -> " + newWidth + SPAN_E);
  return newWidth;
}

$("#output").append(SPAN_S + '$("#id2").innerWidth(67)' + SPAN_E);
$("#id2").innerWidth(67);
output("#id1", "#id2");

$(".change").innerWidth(funcChange);
output("#id3", "#id4");
</script>

#id1
#id2
#id3
class change
#id4
class change