我正在尝试读取图像的大小并调整其边距(如果其高度大于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是否太慢而无法读取height属性?
我希望有一个人可以帮助我!
最佳答案
将当前放置在complete
中的代码移到coverImg.onload
处理程序中。例如:
coverImg.onload = function() {
if(document.getElementById('userCover').height > 150) {
var regulate = (150 - this.height) / 2;
// ...
}
}
coverImg.src = dataArray[1];
...因为浏览器只有在完全加载
<img>
元素之后才能确定其高度-在此之前会触发complete
回调。关于javascript - Javascript太慢了吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22747534/