我显示了一张图片(一个字母)。可以通过按其他字母按钮(change_letter 函数)来更改图像。每个字母都有不同的宽度(从“I”的 18px 到“W”的 35px)。我想将所有字母放在 div 中并使用
margin-left:-width/2+"px"
为此。但是,我得到的宽度值始终是前一张图像的宽度值。因此,在我将字母从“W”(35px)更改为“I”(18px)后,“I”的边距为:-17.5px(W 的),而不是 -9px。
我想知道如何立即获取新图像的宽度。
change_letter: function(e) {
var txt = $(e.target).text().toLowerCase();
if (this.typeFace !==2) {
$('#customlogo_layer2').attr('src',function(_,old_src){
return old_src.replace(/_(\w)_/g,'_'+txt+'_');
});
$('#customlogo_layer3').attr('src',function(_,old_src){
return old_src.replace(/_(\w)_/g,'_'+txt+'_');
});
var layer2img = document.getElementById('customlogo_layer2');
var layer2width = layer2img.clientWidth;
var layer3img = document.getElementById('customlogo_layer3');
var layer3width = layer3img.clientWidth;
$('#customlogo_layer2').css({"margin-left":-layer2width/2+"px","margin-right":-layer2width/2+"px"});
$('#customlogo_layer3').css({"display":"block","margin-left":-layer3width/2+"px","margin-right":-layer3width/2+"px"});
}
else
最佳答案
嗨,我想当你得到图像宽度时,图像还没有加载
试试这个:
$('#customlogo_layer2').load(function(){
var layerWidth = $(this)[0].clientWidth;
$(this).css({"margin-left":-layerWidth/2+"px","margin-right":-layerWidth/2+"px"});
})
$('#customlogo_layer3').load(function(){
var layerWidth = $(this)[0].clientWidth;
$(this).css({"display":"block","margin-left":-layerWidth/2+"px","margin-right":-layerWidth/2+"px"});
})
$('#customlogo_layer2').attr('src',function(_,old_src){
return old_src.replace(/_(\w)_/g,'_'+txt+'_');
});
$('#customlogo_layer3').attr('src',function(_,old_src){
return old_src.replace(/_(\w)_/g,'_'+txt+'_');
});
关于javascript - 获取不断变化的图像宽度的即时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20263961/