这段js的原理很简单,就是通过不断的比较宽度值,然后逐个缩短字符宽度,当最后宽度合适的时候,停止循环,就实现了文字溢出显示…的效果。
(function($) {
$.fn.ellipsis = function(enableupdating){
var s = document.documentelement.style;
if (!('textoverflow' in s || 'otextoverflow' in s)) {
return this.each(function(){
var el = $(this);
if(el.css("overflow") == "hidden"){
var originaltext = el.html();
var w = el.width();
var t = $(this.clonenode(true)).hide().css({
'position': 'absolute',
'width': 'auto',
'overflow': 'visible',
'max-width': 'inherit'
});
el.after(t);
var text = originaltext;
while(text.length > 0 && t.width() > el.width()){
text = text.substr(0, text.length - 1);
t.html(text + "...");
}
el.html(t.html());
t.remove();
if(enableupdating == true){
var oldw = el.width();
setinterval(function(){
if(el.width() != oldw){
oldw = el.width();
el.html(originaltext);
el.ellipsis();
}
}, 200);
}
}
});
} else return this;
};
})(jquery);
这段js还需要一段css来配合。
.overflow {
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
(function($) {
$.fn.ellipsis = function(enableupdating){
var s = document.documentelement.style;
if (!('textoverflow' in s || 'otextoverflow' in s)) {
return this.each(function(){
var el = $(this);
if(el.css("overflow") == "hidden"){
var originaltext = el.html();
var w = el.width();
var t = $(this.clonenode(true)).hide().css({
'position': 'absolute',
'width': 'auto',
'overflow': 'visible',
'max-width': 'inherit'
});
el.after(t);
var text = originaltext;
while(text.length > 0 && t.width() > el.width()){
text = text.substr(0, text.length - 1);
t.html(text + "...");
}
el.html(t.html());
t.remove();
if(enableupdating == true){
var oldw = el.width();
setinterval(function(){
if(el.width() != oldw){
oldw = el.width();
el.html(originaltext);
el.ellipsis();
}
}, 200);
}
}
});
} else return this;
};
})(jquery);
这段js还需要一段css来配合。
.overflow {
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}