溢出文本省略号的js实现
function ellipsis(element) {
var limitWidth = element.clientWidth;
var temp = element.cloneNode(true);
temp.style.float = 'left'; temp.style.width = 'auto';
element.parentNode.appendChild(temp);
var realWidth = temp.clientWidth;
if(realWidth >= limitWidth){
var ellipsisText = '...';
var str = element.innerHTML;
str.replace(/\s+/g, ' ');
temp.innerHTML = ellipsisText;
var s, totalWidth = 0, newHtml = '', oldHtml;
for (var i = 0, len = str.length; i < len; i++) {
s = str.substr(0, i); oldHtml = temp.innerHTML;
newHtml = s + ellipsisText; temp.innerHTML = newHtml;
totalWidth = temp.clientWidth;
if (totalWidth > limitWidth) {
newHtml = oldHtml; break;
}
}
element.innerHTML = newHtml;
}
temp.parentNode.removeChild(temp);
}