其实我写了一个jQuery插件去做这个。它只是设置目标元素到整个文本的title如果截断,但你能适应它为您的具体需求:
/**
* @author ach
*
* Sets the CSS white-space, overflow, and text-overflow properties such that text in the selected block element will
* be truncated and appended with an ellipsis (...) if overflowing. If the text is truncated in such a way, the
* selected element's 'title' will be set to its full text contents and the cursor will be set to 'default'.
* For this plugin to work properly, it should be used on block elements (p, div, etc.). If used on a th or td element,
* the plugin will wrap the contents in a div -- in this case, the table's 'table-layout' CSS property should be set to 'fixed'.
*
* The default CSS property values set by this plugin are:
* white-space: nowrap;
* overflow: hidden;
* text-overflow: ellipsis
*
* @param cssMap A map of css properties that will be applied to the selected element. The default white-space,
* overflow, and text-overflow values set by this plugin can be overridden in this map.
*
* @return The selected elements, for chaining
*/
$.fn.truncateText = function(cssMap) {
var css = $.extend({}, $.fn.truncateText.defaults, cssMap);
return this.each(function() {
var $this = $(this);
//To detect overflow across all browsers, create an auto-width invisible element and compare its width to the actual element's
var element = $this.clone().css({display: 'inline', width: 'auto', visibility: 'hidden'}).appendTo('body');
if (element.width() > $this.width()) {
//If a th or td was selected, wrap the content in a div and operate on that
if ($this.is("th, td")) {
$this = $this.wrapInner('
}
$this.css(css);
$this.attr("title", $.trim($this.text()));
$this.css({"cursor": "default"});
}
element.remove();
});
};
$.fn.truncateText.defaults = {
"white-space" : "nowrap",
"overflow" : "hidden",
"text-overflow" : "ellipsis"
};
和使用,只需JS和拨打:
$(".override").truncateText();
这已被用于生产,并没有注意到页面上数百个目标元素的任何不良影响。