首页 > 代码库 > Js文本溢出自动添加省略号ellipsis

Js文本溢出自动添加省略号ellipsis

原文:
ellipsis: function(value, len, word) {
        //判断value有没有超过指定长度
        if (value && value.length > len) {
            //word的作用就是尽量不让一个完整的单词被部分省略
            if (word) {
                var vs = value.substr(0, len - 2),
                //猜测单词的界限符
                index = Math.max(vs.lastIndexOf(‘ ‘), vs.lastIndexOf(‘.‘), vs.lastIndexOf(‘!‘), vs.lastIndexOf(‘?‘));
//保留一个容忍长度len - 15,过短的话,影响表现效果
                if (index !== -1 && index >= (len - 15)) {
                    return vs.substr(0, index) + "...";
                }
            }
            return value.substr(0, len - 3) + "...";
        }
        return value;
    }
 
经修改:
 function ellipsis(val, len, word) {            if (val && val.length > len) {                if (word) {                    var vs = val.substr(0, len - 1)                    var i = Math.max(vs.lastIndexOf(‘ ‘), vs.lastIndexOf(‘.‘), vs.lastIndexOf(‘!‘), vs.lastIndexOf(‘?‘))                    if ( i !== -1 && i >= (len-15) ) {                        return vs.substr(0, i) + ‘...‘                    }                }                return val.substr(0, len) + ‘...‘            }            return val        }

调用方式:

var aa="你是谁?萨达哈撒"; var bb=ellipsis(aa,5); console.log(bb);

 

Js文本溢出自动添加省略号ellipsis