加载图像时如何一次运行一些代码?

时间:2015-03-09 07:04:08

标签: javascript image

我希望在加载页面时获得图像的宽度。因为图像的宽度用于判断某些条件,所以逻辑如下:

var width = $('img').width();
var height = $('img').height();
if(width > height){
  //do fn1
}else{
  //do fn2
}

Here is a link来模拟我的问题。我知道使用函数setTimeout是否会延迟  获得图像宽度可用,但不准确。

4 个答案:

答案 0 :(得分:3)

这是jQuery文档中给出的示例

...带有简单图片的页面:

<img src="book.png" alt="Book" id="book">

事件处理程序可以绑定到图像:

$( "#book" ).load(function() {
  // Handler for .load() called.
});

一旦加载了图像,就会调用处理程序。

http://api.jquery.com/load-event/

以下是有助于您解决问题的更多信息:

How to get image size (height & width) using JavaScript?

答案 1 :(得分:2)

或者,如果你很棒,你可以创建图像元素,添加源,并在加载时执行某些操作。不需要jQuery。

var image = new Image();
image.onload = function() {
    alert('image loaded');
};
image.src = 'image/image.jpg';

答案 2 :(得分:0)

object.onload=function(){
var width = $('img').width();
height = $('img').height();
};

你可以尝试这个onload功能。

答案 3 :(得分:0)

加载图像后应检查图像宽度和高度。 使用JQuery,您可以像这样检查页面加载:

    $('img').load(function() {
          var width =  $('img').width();
          var height = $('img').height();

          if(width > height){
            console.log(1);
          }else{
            console.log(2);
          }
    });

JS BinExample Here