javascript - 获取不断变化的图像宽度的即时更新

标签 javascript jquery css

我显示了一张图片(一个字母)。可以通过按其他字母按钮(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/

相关文章:

html - CSS背景和正文高度100%

javascript - 使用 Jekyll、react 和 webpack 实例化对象的问题

javascript - 没有旋转的转换属性的 CSS 转换

javascript - 根据变量的长度多次调用突变

javascript - 使用 jQuery 按索引获取 td

CSS calc 的 jQuery 回退函数

jquery - jQuery 中的 Toggle 和 slideToggle 有什么区别?

javascript - 无论屏幕大小/宽度如何,我都希望将 html 表单保留在响应式幻灯片图像上

css - 在 IntelliJ IDEA Ultimate 版本 14 中配置 LESS 编译器?

javascript - 强制手机有 1000px 宽度