Javascript太慢了?

时间:2014-03-30 17:50:35

标签: javascript jquery css ajax

我试图读取图像的大小并调整其边距,如果它的高度大于150。但我总是得到一个' 0'运行此代码时在控制台中:

        var coverImg;
        coverImg = document.getElementById('userCover');

        $.ajax({
                type: "POST",
                url: 'code/submit/submitGetUserData.php',
                data: {id: userID, what: 'all'},
                async: false,
                success:function(data,status){
                    var dataArray = data.split(',');

                    document.getElementById('userAvatar').src = dataArray[0];
                    coverImg.src = dataArray[1];
                    $('#userName').text(dataArray[2]);
                },
                error: function(){
                    alert("error occured");

                },
                complete: function(){
                    console.log(coverImg.height);

                    if(document.getElementById('userCover').height > 150)
                    {
                        var regulate = 0;
                        regulate = (coverImg.height - 150) / 2;
                        regulate = regulate * (-1);



                        coverImg.style.marginTop = regulate;
                    }
                }
        });

JS读取高度属性太慢了吗?!

我希望有人可以帮助我!

1 个答案:

答案 0 :(得分:5)

将当前放置在complete中的代码移动到coverImg.onload处理程序中。例如:

coverImg.onload = function() {
   if(document.getElementById('userCover').height > 150) {
     var regulate = (150 - this.height) / 2;
     // ...
   }
}
coverImg.src = dataArray[1];

...因为浏览器只有在完全加载后才能确定<img>元素的高度 - 并在此之前触发complete回调。