最近实习,记录一下遇到的问题。
这个问题主要是实现边框项目文本超过一定宽度显示省略号的功能。
最开始的需求描述是超过6个字符直接显示省略号,这个直接判断length就行。
后来mentor说可以优化一下,比如说数字、字母、汉字的宽度是不一样的,设置成固定宽度,超出显示省略号会更合理。
js动态计算字符串宽度
最开始我的想法是用js动态计算字符串宽度,然后加判断
以下是搜到的方法:
(来源:https://zhuanlan.zhihu.com/p/338634062)
由于像素和字体大小,字节(特别是 UTF-8)等限制因素,所以我们不能直接知道一个字符串所占的实际宽度。
这里提供几种比较测量方法:
1、通过Canvas测
/**
* Uses canvas.measureText to compute and return the width of the given text of given font in pixels.
*
* @param {String} text The text to be rendered.
* @param {String} font The css font descriptor that text is to be rendered with (e.g. "bold 14px verdana").
*
* @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
*/
function getTextWidth(text, font) {
// re-use canvas object for better performance
var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
}
console.log(getTextWidth("hello there!", "bold 12pt arial")); // close to 86
2、通过 DOM 测量,这种方法在字符串中含有多个空格时,测出来的宽度会一样,
例如: ‘‘天猫旗舰店 49.67%(tmall)’’ 和 ‘‘天猫旗舰店 49.67%(tmall)’’ 测出来的宽度都为 165(此值可能会有差异)
function getTextWidth(str = '') {
const dom = document.createElement('span');
dom.style.display = 'inline-block';
dom.textContent = '天猫旗舰店 49.67%(tmall)';
document.body.appendChild(dom);
const width = dom.clientWidth;
console.log(dom.clientWidth);
document.body.removeChild(dom);
return width;
}
3、用个 visibility: hidden 的浮动的层来计算字符串宽度。
在添加的 div 容器里把样式设置为和你实际的 div 一样。
<!DOCTYPE html>
<html>
<head>
<script src='jquery.min.js'></script>
</head>
<body>
<div
id='labelText'
style='color:black; line-height:1.2; white-space: nowrap; position:fixed;
top:0px; left:0px; display:block; visibility:visible;'
></div>
<script>
var str = 'Live like you were dying, Love because you do.';
str = str.substring(0, str.length);
$('#labelText').css({
'font-size': '12px',
'font-family': 'Microsoft YaHei'
}).html(str);
var width = $('#labelText').width();
console.log(width);
</script>
</body>
</html>
计算高度也一样。
最后别忘了移除额外添加的 div!
Code:
let tCanvas = null;
getTextWidth(text, font = 'normal 12px sans-serif') {
// re-use canvas object for better performance
const canvas = tCanvas || (tCanvas = document.createElement('canvas'));
const context = canvas.getContext('2d');
context.font = font;
return context.measureText(text).width;
}
addStrWidthViaBlank(str, width) {
// 这个函数只适用于'xxx xx'形式的字符串(即原串就含有空格)
if (width <= 0 || (this.getTextWidth(str) >= width)) {
return str;
}
let tStr = str;
let tWidth = 0;
while (tWidth < width) {
tStr = tStr.replace(/(.*) /, '$1 ');
tWidth = this.getTextWidth(tStr);
}
// console.log('tStr>width>>tWidth,', tStr, width, tWidth);
return tStr;
}
css实现文本超出一定宽度后显示省略号
mentor给的更优解是直接用css,看来我对css的学习真的欠缺好多,前两天有个需求也是改了好久调不出来,最后也是问人解决的。
css直接设置文本超出一定宽度显示省略号的方法:
(来源:https://blog.csdn.net/u013868665/article/details/78893158)
//单行时
overflow:hidden; //超出的文本隐藏
text-overflow:ellipsis; //溢出用省略号显示
white-space:nowrap; //溢出不换行
//双行时
overflow: hidden;
text-overflow: ellipsis;
display:-webkit-box; //作为弹性伸缩盒子模型显示。
-webkit-box-orient:vertical; //设置伸缩盒子的子元素排列方式--从上到下垂直排列
-webkit-line-clamp:2; //显示的行