css显示两行或多行文字,再显示省略号

本文介绍了一种使用JavaScript实现的两行文本自动换行的方法,通过计算字符宽度来确保文本能在限定的宽度内正确换行。适用于前端开发中需要对文本进行格式化处理的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<style type="text/css">

text-overflow: ellipsis;

-o-text-overflow: ellipsis;

overflow: hidden;

white-space: nowrap;

width; 300px;

height: 30px;

display: block;

</style>


<script>

$(function () {
    $(".two-lines").each(function () {
        var $this = $(this);
        var _width = $this.css("width"), width = parseInt(_width.substring(0, _width.length - 2)); //显示框的长度
        var _text = $this.text();
        var tot = 0.0, str = _text, add = $this.css("font-size"), num = parseInt(add.substring(0, add.length - 2)); //字或字母的长度
        var _char; 
        num += $this.css("font-weight") == "bold" ? 1 : 0;


        for (var i = 0; i < _text.length; ++i) {
            _char = _text.charCodeAt(i);
            if (_char >= 0 && _char <= 128) tot += num / 2;
            else tot += num;
            console.log("tot: " + tot);
            if (tot >= width) {
                str = _text.substring(0, i) + "<br />" + _text.substring(i);
                break;
            }
        }


        $this.html("<nobr>" + str + "</nobr>");
        console.log("width: " + width);
    })
})

</script>


<span class="two-lines"></span>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值