2016年2月26日金曜日

(jQueryの学習)CSS:幅を操作する/outerWidthメソッド/borderの外側の幅を取得する

CSSの幅を操作する方法の3回目です。

本日は「3.borderの外側の幅(border、paddingを含む)を取得する」を学びます。

3.borderの外側の幅(border、paddingを含む)を取得する

3-1.outerWidthメソッド【返却値(数値) = 要素.outerWidth([True])】でborderの外側の幅を取得する
次にouterWidthを取得します。

outerWidthとは「borderの外側の幅」を表します。
つまり、「左右のborder+左右のpadding+width=outerWidth」です。

なお、引数に「True」を設定することで、
「marginを含んだ幅(エリア全体の幅)」を取得することもできます。
つまり、「左右のmargin+左右のborder+左右のpadding+width=outerWidth」です。

利用方法はwidthメソッドと同様。

注意:このメソッドは設定では使用できません。
サンプルソース
// HTML
<input type="button" value="ボタンを押すと、指定した要素の幅が表示されます"><br>
<div class="box">
  <div class="box"><b>テストエリア1</b><div class="box-css-test-area-1">・・・略・・・</div></div>
</div>

// CSS
/* テストエリア1 */
.box-css-test-area-1 {background:#F5EEFF; border:5px solid #88f; padding:10px; margin:20px; height:40px; width:460px;}

// jQuery
$(function() {
  $("input[type=button]").click(function(){
    // 【構文】返却値(数値) = 要素.outerWidth([True])
    //   サンプル:「テストエリア1」のborderの外側の幅を取得する
    alert("[" + $(".box-css-test-area-1").outerWidth() + "]");     // marginを含まない
    alert("[" + $(".box-css-test-area-1").outerWidth(True) + "]"); // marginを含む
  });
});
実装例
指定した要素に設定されているborderの外側の幅を取得します。

要素:  marginも含む:

テストエリア1
border:5px; padding:10px; margin:20px; height:40px; width:460px;
(境界線:5px、枠内余白:10px、枠外余白:20px、高さ:40px、幅:460px)
テストエリア2
border:5px; padding:20px; margin:10px; height:30px; width:450px;
(境界線:5px、枠内余白:20px、枠外余白:10px、高さ:30px、幅:450px)

いかがでしたか?
CSSの幅を操作する方法や、
width、innerWidth、outerWidthの違いが分かったと思います。

それでは、また。

Previous Post
Next Post

post written by: