LoginSignup
2
0

More than 5 years have passed since last update.

要素の縦横サイズを小数点以下も含めて取得する

Last updated at Posted at 2017-11-03

jQuery1系では小数点以下のサイズが取得できず困ったため備忘録。
Web APIの「getComputedStyle」で取得できる。
古いWebブラウザでは一部仕様が異なるか、非対応。参照元が詳しい。

(function ($) {
    "use strict";

    // Document ready
    $(function () {

            $('.target').each(function(i) {
                var tag = $(this).get(0).tagName.toLowerCase();
                if(tag === 'img'){

                    var style, w, h;
                    if (getComputedStyle) {
                        style = getComputedStyle($(this).get(0), '');
                        w = style.getPropertyValue('width');
                        h = style.getPropertyValue('height');
                    } else {
                        // for ie8 or less
                        style = $(this).get(0).currentStyle();
                        w = style.width;
                        h = style.height;
                    }

                    console.log('No.' + i + ' = width:' + w + ' height:' + h);

                }else{
                    console.log('not img tag : ' + tag + ' ' + i);
                }
            });

    });
})(jQuery);

【参照元】

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0