我正在尝试修改这个 jquery truncate 插件,以便我可以: - 在不使用选择器的情况下手动调用它 - 并传递给我想要截断的文本。
这是否可以创建一个可以在外部调用的公共方法?
/*
* Truncate a piece of text to a predefined amount of lines.
* It assumes pixel values of both the container and its line-height.
* Useful when you have multiple boxes with text in your design that require equal heights
*/
$.fn.truncateLines = function(options) {
var defaults = {
delay: 100,
text: false,
minusHeight: 0
};
options = $.extend(defaults, options);
function truncate(index, container){
container = $(container);
var containerLineHeight = Math.ceil(parseFloat(container.css('line-height'))),
maxHeight = options.lines * containerLineHeight,
truncated = false,
truncatedText = $.trim(container.text()),
overflowRatio = container.height() / maxHeight;
if (overflowRatio > 2) {
// slice string based on how much text is overflowing
truncatedText = truncatedText.substr(0, parseInt(truncatedText.length / (overflowRatio - 1), 10) + 1);
container.text(truncatedText);
truncated = true;
}
var oldTruncatedText; // verify that the text has been truncated, otherwise you'll get an endless loop
while (container.height() > maxHeight && oldTruncatedText != truncatedText) {
oldTruncatedText = truncatedText;
// remove last word
truncatedText = truncatedText.replace(/\s.[^\s]*\s?$/, '');
container.text(truncatedText);
truncated = true;
}
if (truncated) {
truncatedText = options.ellipsis ? truncatedText + options.ellipsis : truncatedText;
container.text(truncatedText);
if (container.height() > maxHeight) {
// remove last word and ellipsis
truncatedText = truncatedText.replace(/\s.[^\s]*\s?...$/, '');
truncatedText = options.ellipsis ? truncatedText + options.ellipsis : truncatedText;
container.text(truncatedText);
}
}
}
// Loop selectors
return this.each(truncate(index, container));
};