页面上标签过多,极致版处理
我们常常会遇到页面上标签太多,但是设计希望不去换行显示,直接截断的话样式又不美观,能做的处理办法就是根据当前整个标签组一整行的总宽度,去计算每一个标签加上padding+margin+文字本身的宽度值,看最终能放下几个,放不下的标签在循环的时候将是否显示设置为false就可以了。
接下来上代码!!
let containerWidth = 240
let sumWidth = 0 // tag-item元素宽度的累加和
let tagWidth = 0
all_tags.forEach((item, index) => {
if (item.type == 'icon') {
tagWidth = 24
} else {
let word = item.name
let wordWidth = _this.getLenPx(word, 11)
tagWidth = wordWidth + 4 * 3 + 2
}
if (sumWidth + tagWidth > containerWidth) {
all_tags[index].isShow = false // 将多出的tag-item元素截断
} else {
all_tags[index].isShow = true
sumWidth += tagWidth
}
})
//将元素换算计算大小
getLenPx: function (str, font_size) {
var str_leng = str.replace(/[^\x00-\xff]/gi, 'aa').length
return (str_leng * font_size) / 2
},