2 回答
TA贡献1865条经验 获得超7个赞
我写了一个原生的 JavaScript 版本:
function wrapNewLines(targetSelector, wrapEl = 'span', wrapClass = 'new-line') {
const content = document.querySelectorAll(targetSelector)
content.forEach(section => {
let sectionWidth = section.getBoundingClientRect().width
let words = section.innerText.split(/( )/g)
section.innerHTML = words.map(word =>`<span>${word}</span>`).join('')
let lines = []
let line = []
let lineWidth = 0
let spans = section.querySelectorAll('span')
spans.forEach((span, i) => {
let spanWidth = span.getBoundingClientRect().width
if (lineWidth + spanWidth <= sectionWidth - 4) {
line.push(span)
lineWidth += spanWidth
} else {
lines.push(line)
line = []
lineWidth = 0
line.push(span)
lineWidth += spanWidth
}
})
if (line.length) lines.push(line)
let newLines = lines
.map(
line =>
`<${wrapEl} class=${wrapClass}>${line
.map(span => span.innerText)
.join('')}</${wrapEl}>`
)
.join('')
section.innerHTML = newLines
})
}
wrapNewLines ('.emails .multi-items .message-contain #content');
TA贡献1784条经验 获得超9个赞
试试下面的代码
$(".emails .multi-items").each(function(i) {
var $cont = $(".message-contain #content");
var text_arr = $cont.text().split(". ");
for (i = 0; i < text_arr.length; i++) {
text_arr[i] = "<span class='line_wrap'>" + text_arr[i] + ". </span>";
}
$cont.html(text_arr.join(""));
});
添加回答
举报