您的位置:首页 > Web前端 > JQuery

用jQuery在图片加载完成后改变图片大小

2012-09-27 17:16 197 查看
要改变图片的大小并不难,可以用jQuery操作css改变。但是前提是要判断图片是否加载完成。主要是通过jQuery的load事件和onreadystatechange来判断其状态。

对于IE6,用onreadystatechange可以直接处理,在IE7中,则需要用定时器来判断图片的readystate状态。而对于FF和Chrome刚可以直接用load事件来判断。

以下是在实例中使用的完整代码:

<script type="text/javascript">
$(document).ready(function(){
function changeSize(obj){//本函数用于在图片加载时对图片大小等进行设置
w=obj.width();
h=obj.height();
t=obj.attr("title");
src=obj.attr("src");
obj.width(w>400?400:w);
obj.height(w>400?(400/w)*h:h);
obj.css("cursor","pointer");
obj.click(function(){
$("#picDlg").html("<img src="+src+" border=0/>").fadeIn(1000).dialog({
width:"auto",
height:"auto",
title:t,
modal:true,
draggable:false,
resizable:false
})
})
}
if($.browser.msie){
//IE 6.0
if($.browser.version==6.0){
$(".bodyLeft img").each(function(ind,ele){
// ele.onreadystatechange =function(){
if(ele.readyState == "complete"||ele.readyState=="loaded"){
changeSize($(this));
}
//}
})
}
//IE 6.0以上
else{
$(".bodyLeft img").each(function(){
tempTimer=window.setInterval(function(ind,ele){
if(ele.readyState=="complete"){
window.clearInterval(tempTimer);
changeSize($(this));
}
else{
return;
}
},200);
})
}
}
//FF,Chrome
else{
$(".bodyLeft img").each(function(ind,ele){
alert(ele.complete);
if(ele.complete==true){
changeSize($(this));
}
})
}
})
</script>


上面的图片可以将图片等比例缩小显示在文章中,同时使用的jQuery的Dialog UI组件单击图片时,以一个层显示完整大小的图片。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: