我正在寻找一个简单的脚本,它可以用省略号 (...)
我想截断像'this is a very long string'
到'this is a ve...'
我不想使用 CSS 或 PHP。
我正在寻找一个简单的脚本,它可以用省略号 (...)
我想截断像'this is a very long string'
到'this is a ve...'
我不想使用 CSS 或 PHP。
function truncate(input) {
if (input.length > 5) {
return input.substring(0, 5) + '...';
}
return input;
};
或在 ES6 中
const truncate = (input) => input.length > 5 ? `${input.substring(0, 5)}...` : input;
KooiInc 对此有一个很好的回答。总结一下:
String.prototype.trunc =
function(n){
return this.substr(0,n-1)+(this.length>n?'…':'');
};
现在你可以这样做:
var s = 'not very long';
s.trunc(25); //=> not very long
s.trunc(5); //=> not...
如果你更喜欢它作为一个函数,根据@AlienLifeForm 的评论:
function truncateWithEllipses(text, max)
{
return text.substr(0,max-1)+(text.length>max?'…':'');
}
对此,KooiInc 全权负责。
这会将其限制为您希望限制的多行并且是响应式的
一个没有人提出过的想法,根据元素的高度来做,然后从那里剥离它。
小提琴 - https://jsfiddle.net/hutber/u5mtLznf/ <- ES6 版本
但基本上你想获取元素的行高,遍历所有文本并在达到特定行高时停止:
'use strict';
var linesElement = 3; //it will truncate at 3 lines.
var truncateElement = document.getElementById('truncateme');
var truncateText = truncateElement.textContent;
var getLineHeight = function getLineHeight(element) {
var lineHeight = window.getComputedStyle(truncateElement)['line-height'];
if (lineHeight === 'normal') {
// sucky chrome
return 1.16 * parseFloat(window.getComputedStyle(truncateElement)['font-size']);
} else {
return parseFloat(lineHeight);
}
};
linesElement.addEventListener('change', function () {
truncateElement.innerHTML = truncateText;
var truncateTextParts = truncateText.split(' ');
var lineHeight = getLineHeight(truncateElement);
var lines = parseInt(linesElement.value);
while (lines * lineHeight < truncateElement.clientHeight) {
console.log(truncateTextParts.length, lines * lineHeight, truncateElement.clientHeight);
truncateTextParts.pop();
truncateElement.innerHTML = truncateTextParts.join(' ') + '...';
}
});
CSS
#truncateme {
width: auto; This will be completely dynamic to the height of the element, its just restricted by how many lines you want it to clip to
}
就像是:
var line = "foo bar lol";
line.substring(0, 5) + '...' // gives "foo b..."
用于防止在单词中间或标点符号之后出现点。
let parseText = function(text, limit){
if (text.length > limit){
for (let i = limit; i > 0; i--){
if(text.charAt(i) === ' ' && (text.charAt(i-1) != ','||text.charAt(i-1) != '.'||text.charAt(i-1) != ';')) {
return text.substring(0, i) + '...';
}
}
return text.substring(0, limit) + '...';
}
else
return text;
};
console.log(parseText("1234567 890",5)) // >> 12345...
console.log(parseText("1234567 890",8)) // >> 1234567...
console.log(parseText("1234567 890",15)) // >> 1234567 890