开发者

Calculating width of div with various text not working in Firefox v.7

I have created a script to determine whether a div will expand past a 130px width wh开发者_运维知识库en various words are placed in it. The script is based on Deepak Nadar's solution at: Calculate text width with JavaScript

My issue is that it appears that the outerWidth is returned prior to the injected div being ready. I have inserted 2 alerts before my while loop. Can anyone tell me why I am getting two values, and better yet, how to defer returning outerWidth until the element is ready? Thanks!

    for(i in words){

      var div = document.createElement('div');
      document.body.appendChild(div);
          $(div).css({
           position: 'absolute',
           left: -1000,
           top: -1000,
           display: 'none'
          });                 

            $(div).html(words[i]);

            var styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing'];

              var $this = $(this)

              $(styles).each(function() {
               var s = this.toString();
               $(div).css(s, $this.css(s));
              });

              alert($(div).outerWidth()); //Returns incorrect value of 121
              alert($(div).outerWidth()); //Returns correct value of 134

            while($(div).outerWidth() > MAXWIDTH){
                FONTSIZE--;
                $(div).css('font-size', FONTSIZE + 'px');
                $(this).css('font-size', FONTSIZE + 'px');
                }                       
            }       }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜