有一个需求,移动端用户需要根据从后端获取的标题太长的时候显示隐藏
一开始我的想法是获取字符串长度,截取字符串后拼接…
但是转念一想手机屏幕尺寸不一,展示的效果可能千差万别,例如若截取10个字为长度,后续用…接上的话,‘abcdefghij’和‘一二三四五六七八九十’,字符串长度上是一样,但是真实效果长度不一样
他们的.length都是10,那么遇到英文过多的时候,可能移动端看上去就会有留白过多的情况
这样好吗?这不好。
获取字符串长度被pass掉了
我选择获取容器宽度和文本宽度来进行比较,当文本宽度>=容器宽度时候
隐藏多余部分并且…,再给个展示按钮,反之,理论存在,实践开始,写个demo
大概就是这种效果
贴一下demo代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.PhoneBox {
width: 375px;
height: 600px;
border: 1px solid greenyellow;
}
.textTitle {
width: 100%;
display: block;
}
#textMain {
display: inline-block;
background: yellow;
}
#menu {
float: right;
background: red;
}
.noText{
width: 100%;
overflow: none;
white-space: normal;
}
.showText{
width: 87%;
overflow: hidden;
text-overflow:ellipsis;
white-space: nowrap;
}
.none{
display: none;
}
</style>
</head>
<body>
<div class="PhoneBox">
<div class="textTitle">
<div id="text">
<span id="textMain">标题长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长</span>
<div id="menu">
<span class="textBtn" id="unfold">(展开)</span>
<span class="textBtn none" id="packUp">(收起)</span>
</div>
</div>
</div>
</div>
</body>
<script>
let box = document.querySelectorAll('#text')[0] //容器
let isOverflow = document.querySelectorAll('#textMain')[0] //文本
let btn1 = document.querySelectorAll('#unfold')[0] //展开按钮
let btn2 = document.querySelectorAll('#packUp')[0] //收起按钮
let menuBox = document.querySelectorAll('#menu')[0] //菜单
let cWidth = box.clientWidth;//获取容器宽度
let sWidth = isOverflow.scrollWidth;//获取文本宽度
if (sWidth >= cWidth) { //当文本长度大于容器长度时 显示缩率标题
isOverflow.classList.add('showText')
menuBox.style.display = 'block'
}else{
isOverflow.classList.add('noText')
menuBox.style.display = 'none'
}
btn1.onclick = function () {
btn2.style.display = 'block'
btn1.style.display = 'none'
isOverflow.classList.remove('showText')
isOverflow.classList.add('noText')
}
btn2.onclick = function () {
btn1.style.display = 'block'
btn2.style.display = 'none'
isOverflow.classList.remove('noText')
isOverflow.classList.add('showText')
}
</script>
</html>