<script>
$(document).ready(function(){
$(".pic_name img").each ( function(){
var maskHeight = $(this).height();
var v1 = (168 - maskHeight)/2 + "px";
$(this).css ( "margin-top", v1)})
 })
</script>
代码我这样写的 是想让一个图片在一个div居中
但是 图片输入到DIV的时候 第一次加载的时候不居中
我要刷新了页面图片才能居中 是为什么呢?

解决方案 »

  1.   

    因为图片没加载完成啊,你获取不到图片的高度。
    var maskHeight = $(this).height();// 这里获取的是0如果你的pic_name里面只有图片的话,可以用CSS搞定<style type='text/css'>
        .pic_name{ height:168px; line-height:168px;}
        .pic_name img{ vertical-align:middle;}
    </style><div class='pic_name'>
        <img src='http://avatar.profile.csdn.net/A/C/F/2_noapple1000.jpg' />
    </div>
      

  2.   


    用 js 可以这样。。$(".pic_name img").each(function(){
        var self = $(this);
        var image = new Image();
        image.src = img.src;
        if (img.complete){
            self.css("margin-top",((168-self.height())/2)+"px");
        }else{
            image.onload = function(){
                self.css("margin-top",((168-this.height)/2)+"px");
            }
        }
    });
      

  3.   

    $(".pic_name img").each(function(){
        var self = $(this);
        var image = new Image();
        image.src = img.src;
        if (image.complete){ // 上面这里写错了。img改为image
            self.css("margin-top",((168-self.height())/2)+"px");
        }else{
            image.onload = function(){
                self.css("margin-top",((168-this.height)/2)+"px");
            }
        }
    });