jQuery Trim String按宽度 [英] jQuery Trim String by Width

查看:114
本文介绍了jQuery Trim String按宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将字符串修剪成特定的像素宽度,以便它可以正确地放入容器中.它将类似于子字符串,除了我根据像素宽度(而不是字符数)进行修剪.有内置的功能吗?

I want to trim a string down to a particular pixel width so that it can properly fit in a container. It will be similar to substring, except that I am trimming based on pixel width as opposed to number of characters. is there a built in function for this?

推荐答案

您可以通过CSS执行此操作:text-overflow: clip;

You can do it via css: text-overflow: clip;

注意:FF<中不支持此功能. 7.其他所有包含IE6的浏览器都支持它.

Note: This is not supported in FF < 7. Every other browser including IE6 supports it.

尝试一下:

function trimByPixel(str, width) {
    var spn = $('<span style="visibility:hidden"></span>').text(str).appendTo('body');
    var txt = str;
    while (spn.width() > width) { txt = txt.slice(0, -1); spn.text(txt + "..."); }
    return txt;
}

这篇关于jQuery Trim String按宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆