Calculating text width

后端 未结 22 1373
轻奢々
轻奢々 2020-11-22 03:36

I\'m trying to calculate text width using jQuery. I\'m not sure what, but I am definitely doing something wrong.

So, here is the code:

var c = $(\'.c         


        
22条回答
  •  自闭症患者
    2020-11-22 04:05

    Neither Rune's nor Brain's was working for me in case when the element that was holding the text had fixed width. I did something similar to Okamera. It uses less selectors.

    EDIT: It won't probably work for elements that uses relative font-size, as following code inserts htmlCalc element into body thus looses the information about parents relation.

    $.fn.textWidth = function() {
        var htmlCalc = $('' + this.html() + '');
        htmlCalc.css('font-size', this.css('font-size'))
                .hide()
                .prependTo('body');
        var width = htmlCalc.width();
        htmlCalc.remove();
        return width;
    };
    

提交回复
热议问题