JSFiddle - React, Tailwind, and code Playground
by Wolfsilver
HTML
<title>javascript文字截断</title>
<body>
<div class="total_container">
<p id="text-one"></p>
<p id="text-two"></p>
</div>
</body>
CSS
@charset"utf-8";
/*reset*/
a img {
border:none;
}
a {
text-decoration:none;
}
em, var {
font-style:normal;
}
ul, ol {
padding:0;
list-style-type:none;
}
body, dl, dd, ul, ol, h1, h2, h3, h4, h5, h6, form, p {
margin:0;
}
body, td, th, h1, h2, h3, h4, h5, h6 {
font-size:12px;
}
input, textarea, a, button {
outline:none;
}
input::-moz-focus-inner {
border:0;
}
body {
color:#333;
line-height:1.125;
}
a:hover {
text-decoration:underline;
}
.total_container {
width:120px;
margin:20px auto;
padding:5px;
border:1px dashed #999;
font-size:14px;
line-height:2;
}
JavaScript
// text-truncation.js
var truncation = (function () {
var Constants = {
SUFFIX: "..."
};
var doc = document,
body = doc.getElementsByTagName("body")[0];
return {
doOne: function (string, widthLimit, targetStyles) {
var containerNode = doc.createElement("div"),
width = 0,
suffix = Constants.SUFFIX,
i;
for (i in targetStyles) {
if (targetStyles.hasOwnProperty(i)) {
containerNode.style[i] = targetStyles[i];
}
}
containerNode.style.position = "absolute";
body.appendChild(containerNode);
containerNode.innerHTML = string;
width = containerNode.offsetWidth;
if (width < widthLimit) {
body.removeChild(containerNode);
return string;
}
while (width > widthLimit) {
string = string.substr(0, string.length - 1);
containerNode.innerHTML = string + suffix;
width = containerNode.offsetWidth;
}
string = string + suffix;
body.removeChild(containerNode);
return string;
},
doMultiple: function (string, lineLimit, lastWidthLimit, targetStyles) {
var containerNode = doc.createElement("div"),
textNode = doc.createElement("span"),
lastRect = null,
lastWidth = 0,
line = 0,
suffix = Constants.SUFFIX,
clientRects,
i;
// targetStyles包含了最终文字会被存放的元素的排版有关样式,临时元素需要和它一样
for (i in targetStyles) {
if (targetStyles.hasOwnProperty(i)) {
containerNode.style[i] = targetStyles[i];
}
}
containerNode.style.position = "absolute";
containerNode.appendChild(textNode);
...