您的位置:首页 > 其它

设置div正方形--快速获得图片真实的宽度和高度

2015-06-16 14:36 232 查看
$(window).load(function() {

//获取div的宽度,设置div正方形

var width1=document.getElementById("div1").offsetWidth;

$("#div1").css("height",width1).find("img").show();

//获取图片的真实宽高

var _w=parseInt($(window).width());

$(".con02 img").each(function(){

var img = $(this);

var realWidth;//真实的宽度

var realHeight;//真实的高度

$("<img/>").attr("src", $(img).attr("src")).load(function() {

realWidth = this.width;

realHeight = this.height;

if(realWidth>=_w){

$(img).css("width","100%").css("height","auto");

}

else{

$(img).css("width",realWidth+'px').css("height",realHeight+'px');

}

})

})

})

网上发现一个定时检测图片宽高的方法,效率非常高。具体代码如下:
代码如下复制代码
// 记录当前时间戳

var start_time = new Date().getTime();

// 图片地址

var img_url = 'img/bdlogo.png?'+start_time;

// 创建对象

var img = new Image();

// 改变图片的src

img.src = img_url;

// 定时执行获取宽高

var check = function(){

// 只要任何一方大于0

// 表示已经服务器已经返回宽高

if(img.width>0 || img.height>0){

var diff = new Date().getTime() - start_time;

document.body.innerHTML += '

from:check : width:'+img.width+',height:'+img.height+', time:'+diff+'ms

';

clearInterval(set);

}

};

var set = setInterval(check,40);
转载链接:http://www.111cn.net/wy/js-ajax/68065.htm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: