是否有JavaScript或jQuery API或方法来获取页面上图像的尺寸?


当前回答

jQuery的答案:

$height = $('#image_id').height();
$width  = $('#image_id').width();

其他回答

使用jQuery,你可以这样做:

var imgWidth = $("#imgIDWhatever").width();

您可以通过编程方式获取图像并使用JavaScript检查尺寸…

const img = new Image(); img。Onload = function() { 警报(这。Width + 'x' + this.height); } img。src = 'http://www.google.com/intl/en_ALL/images/logo.gif';

如果图像不是标记的一部分,这可能很有用。

在获取元素的属性之前,文档页面应该是onload的:

window.onload = function(){
    console.log(img.offsetWidth,img.offsetHeight);
}

用jQuery库-

使用.width()和.height()。

更多jQuery宽度和jQuery高度。

示例代码:

$(文档)时函数(){ $("按钮”).click(函数() { alert(”图像的宽度 : " + $("# img_exmpl”).width ()); alert("形象的高度 : " + $("# img_exmpl”).height ()); }); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js " > < /脚本> <img id="img_exmpl" src="http://images.all-free-download.com/images/graphicthumb/beauty_of_nature_9_210287.jpg"> <button> img显示尺寸</button>

简单地说,您可以像这样进行测试。

  <script>
  (function($) {
        $(document).ready(function() {
            console.log("ready....");
            var i = 0;
            var img;
            for(i=1; i<13; i++) {
                img = new Image();
                img.src = 'img/' + i + '.jpg';
                console.log("name : " + img.src);
                img.onload = function() {
                    if(this.height > this.width) {
                        console.log(this.src + " : portrait");
                    }
                    else if(this.width > this.height) {
                        console.log(this.src + " : landscape");
                    }
                    else {
                        console.log(this.src + " : square");
                    }
                }
            }
        });
    }(jQuery));
  </script>