gpt4 book ai didi

javascript - 如何使用 javascript 和 css 显示固定为 div 宽度的字符串数组中的更多剩余文本?

转载 作者:太空宇宙 更新时间:2023-11-04 07:53:12 25 4
gpt4 key购买 nike

enter image description here

我想在 div 中显示以逗号分隔的字符串数组具有宽度(例如:300 像素)。当文本长于div宽度时,会显示文本有三个点和+(数组中剩余文本的数量),如上图。

谢谢。

最佳答案

这个怎么样?

var main = document.querySelector('main');
var p = document.querySelector('p');
var stringArr = ['Apple', 'Grape fruit', 'Orange', 'Banana', 'KiwiJuice', 'Tangerine'];

function dotdotdot(list){
var ix, ixLen, listLen;
var span = document.createElement('span');
span.textContent = ' + ';

// 1. insert a text into an element
// 2. compare the scrollWidth and the clientWidth
// if scrollWidth is bigger than the other, it means the text has been overflowed
// 3. find the index of the text which has been overflowed
// 4. insert <span>+ ?more</span>
// * when compare two scrollWidths, consider the width of <span> because of the max-width of <main> tag.
// * the width of <span> is set by 150 px as an example.
for(ix = 0, ixLen = list.length; ix < ixLen; ix++){
if(ix !== ixLen - 1){
//main.textContent += list[ix] + ', ';
p.textContent += list[ix] + ', ';
}else{
//main.textContent += list[ix];
p.textContent += list[ix];
}

if(p.scrollWidth > main.scrollWidth - 150){
//p.style.overflow = 'hidden';
//p.style.textOverflow = 'ellipsis';
p.style.width = p.clientWidth + 'px';

span.textContent += list.length - (ix + 1);
span.textContent += 'more';
main.append(span);
return;
}
}
}

dotdotdot(stringArr);
main {
max-width: 300px;
height: 30px;
border: 1px solid #000000;
}

p {
display: inline-block;
width: fit-content;
margin: 0;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
<main>
<p></p>
</main>

关于javascript - 如何使用 javascript 和 css 显示固定为 div 宽度的字符串数组中的更多剩余文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47565429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com