请大家帮我看看,为什么下面代码浏览器第一次执行会有问题,比如ie、firefox、谷歌等都是这样,需要刷新一下才正常。什么原因造成的?应该怎么改。谢谢~~
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style>
#div1 {
    width:500px;
    height:500px;
}
</style>
<script>
function displayImage(XelementId,XimageSrc)
{
    var image=new Image();
    image.src=XimageSrc;
    var div=document.getElementById(XelementId);
    div.style.background="url("+XimageSrc+") no-repeat";
    div.style.backgroundPosition=(500-image.width)/2+"px "+(500-image.height)/2+"px";
}
</script>
</head>
<body onload='displayImage("div1","2.jpg")'>
<div id="div1"></div>
</body>
</html>

解决方案 »

  1.   

    要写成一行吧 
    div.style.backgroundPosition=(500-image.width)/2+"px "+(500-image.height)/2+"px";
      

  2.   

    我猜猜是因为写代码的时候那个图片没有load下来,浏览器不知道宽度和高度。所以认为宽度和高度都为0刷新的时候就不一样了,因为已经加载过一遍了,所以浏览器应该是记住了宽度和高度。该为下面的代码就ok了。
    <script>
    function displayImage(XelementId,XimageSrc)
    {
        var image=new Image();
        image.src=XimageSrc;
        var div=document.getElementById(XelementId);
        div.style.background="url("+XimageSrc+") no-repeat";
    image.onload=function(){
    div.style.backgroundPosition=(200-image.width)/2+"px "+(200-image.height)/2+"px";
    }
    }
    </script>
      

  3.   

    4楼的说法经过验证是正确的,现在其他浏览器下都正常了,唯独ie6不正常,image.onload似乎没有起作用,再想想看怎么解决
      

  4.   

    现在我为了使ie6下也正常,先直接设,然后再给image.onload设,这样没问题,各浏览器下都正常。但是我想看看有没有更好的办法?
    [code=HTML][function displayImage(XelementId,XimageSrc)
    {
        var image=new Image();
        image.src=XimageSrc;
        var div=document.getElementById(XelementId);
        div.style.background="url("+XimageSrc+") no-repeat";
        div.style.backgroundPosition=(500-image.width)/2+"px "+(500-image.height)/2+"px";
        image.onload=function(){
            div.style.backgroundPosition=(500-image.width)/2+"px "+(500-image.height)/2+"px";
        }
    }/code]
      

  5.   

    将image.src=XimageSrc;放到最后面
    <script>
    function displayImage(XelementId,XimageSrc)
    {
        var image=new Image();
        var div=document.getElementById(XelementId);
        div.style.background="url("+XimageSrc+") no-repeat";
        image.onload=function(){
         div.style.backgroundPosition=(200-image.width)/2+"px "+(200-image.height)/2+"px";    
        }
    image.src=XimageSrc;
    }
    </script>
      

  6.   

    测试了一下,可以了,多谢各位捧场!尤其感谢hackerster0324解决问题。