5

JQuery 计算文本的总宽度(Width)

 2 years ago
source link: https://blog.p2hp.com/archives/9227
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JQuery 计算文本的总宽度(Width)

JQuery计算文本宽度的原理是利用html提供的<pre>标签,向dom中动态添加<pre>标签,标签里的内容就是要测试长度的文本,获取完长度之后再删除刚才添加的<pre>标签,从而可取到文本的大概长度了。

为什么要用标签而不用其他标签呢,那来看看<pre>标签的特性吧:pre 元素可定义预格式化的文本。被包围在 pre 元素中的文本通常会保留空格和换行符;而文本也会呈现为等宽字体。 <pre>标签的一个常见应用就是用来表示计算机的源代码。需要注意的地方是,计算文本长度时文本里面最好不要有其他标签。

以下是实现代码:

    function GetCurrentStrWidth(text, font) {
        var currentObj = $('<pre>').hide().appendTo(document.body);
        $(currentObj).html(text).css('font', font);
        var width = currentObj.width();
        currentObj.remove();
        return width;
    }

在此提供另外一种实战中验证过的方法: 完全可以用span 标签去替代 pre 标签。 只不过我们要十分注意:要传递正确的font信息(包括:font-family, font-size, font-weight)

计算文本长度的代码方法:

    function GetCurrentStrWidth(text, font) {
        var currentObj = $('<span>').hide().appendTo(document.body);
        $(currentObj).html(text).css('font', font);
        var width = currentObj.width();
        currentObj.remove();
        return width;
    }

调用方式:

    var currentFont = "normal 13px Helvetica, Arial, sans-serif";
    var currentText = "111111111111";
    var currentWidth = GetCurrentStrWidth(currentText, currentFont);

。。。。。。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK