- 基础:css单行文本溢出(4个属性)
.box {
width: 200px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
- 不考虑兼容(safari, chrome等,见拓展)的css多行文本溢出(5个属性)
.box {
width: 200px;
overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2 /*几行就写数字几*/
}
- 考虑兼容的js写法1
window.onload = function() {
const box = document.querySelector('#box')
const reg = /(?<=[\u4e00-\u9fa5])|(?<=\w*?\b)/g
let words = box.innerText.split(reg)
while(box.scrollHeight > box.offsetHeight) {
words.pop()
box.innerText = words.join('') + '...'
}
}
- 考虑兼容的js写法2
window.onload = function(){
const box = document.querySelector('#box')
const str = box.innerText
for(let i = 0;i < str.length; i++){
box.innerHTML = str.substring(0, i)
if (box.scrollHeight > box.offsetHeight) {
box.innerHTML = str.substring(0, i-3) + '...'
break; // 很重要哦,此时不退出循环内容就超出了
}
}
}
-
拓展
八大webkit内核浏览器- Google Chrome 谷歌浏览器
- Safari浏览器
- 搜狗高速浏览器
- 遨游浏览器3
- QQ浏览器
- 360极速浏览器
- 世界之窗浏览器
- 阿里云浏览器
-
参考
https://muyiy.cn/question/css/127.html