1、首先文字换行和display属性是没有关系的
2、影响文字换行不起作用的有可能是white-space属性
.div{
width:100px;//必须要设置的
white-space:normal;
word-break:break-all;
}
1、首先文字换行和display属性是没有关系的
2、影响文字换行不起作用的有可能是white-space属性
.div{
width:100px;//必须要设置的
white-space:normal;
word-break:break-all;
}
转载于:https://www.cnblogs.com/windseek/p/6400293.html
1、pre文字换行
"pre"标签主要是包裹源代码,默认有overflow:auto则会出现滚动条,代码不方便阅读。
// pre 默认样式 pre { overflow: auto; } pre { display: block; padding: 9.5px; margin: 0 0 10px; font-size: 13px; line-height: 1.42857143; color: #333; word-break: break-all; word-wrap: break-word; background-color: #f5f5f5; border: 1px solid #ccc; border-radius: 4px; } user agent stylesheet pre, xmp, plaintext, listing { display: block; font-family: monospace; white-space: pre; //normal 默认。空白会被浏览器忽略。 //pre 空白会被浏览器保留。其行为方式类似 HTML 中的 <pre> 标签。 //nowrap 文本不会换行,文本会在在同一行上继续,直到遇到 <br> 标签为止。 // !!!! pre-wrap 保留空白符序列,但是正常地进行换行。 //pre-line 合并空白符序列,但是保留换行符。 // inherit 规定应该从父元素继承 white-space 属性的值。 margin: 1em 0px; } // 解决pre换行问题: // 解决办法 修改pre样式、正常换行 pre { white-space: pre-wrap; word-wrap: break-word; }```
引子
近期的工作中,遇到的功能需求,需要控制文字显示行数,超过就省略号显示。
一般文字行数控制用 css 就可以实现,但在 canvas 中不行。在网站查询资料,就可以发现需要程序控制文字换行,主要使用到的方法是 measureText()
,这个方法会返回一个度量文本的相关信息的对象,例如文本的宽度。
这里会有一个边界问题:如果文字在 canvas 边界出现换行,那么就可能出现文字显示不全的问题。
主要处理方法如下:
// 文本换行处理,并返回实际文字所占据的高度
function textEllipsis (context, text, x, y, maxWidth, lineHeight, row) {
if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
return;
}
var canvas = context.canvas;
if (typeof maxWidth == 'undefined') {
maxWidth = canvas && canvas.width || 300;
}
if (typeof lineHeight == 'undefined') {
// 有些情况取值结果是字符串,比如 normal。所以要判断一下
var getLineHeight = window.getComputedStyle(canvas).lineHeight;
var reg=/^[0-9]+.?[0-9]*$/;
lineHeight = reg.test(getLineHeight)? getLineHeight:20;
}
// 字符分隔为数组
var arrText = text.split('');
// 文字最终占据的高度,放置在文字下面的内容排版,可能会根据这个来确定位置
var textHeight = 0;
// 每行显示的文字
var showText = '';
// 控制行数
var limitRow = row;
var rowCount = 0;
for (var n = 0; n < arrText.length; n++) {
var singleText = arrText[n];
var connectShowText = showText + singleText;
// 没有传控制的行数,那就一直换行
var isLimitRow = limitRow ? rowCount === (limitRow - 1) : false;
var measureText = isLimitRow ? (connectShowText+'……') : connectShowText;
var metrics = context.measureText(measureText);
var textWidth = metrics.width;
if (textWidth > maxWidth && n > 0 && rowCount !== limitRow) {
var canvasShowText = isLimitRow ? measureText:showText;
context.fillText(canvasShowText, x, y);
showText = singleText;
y += lineHeight;
textHeight += lineHeight;
rowCount++;
if (isLimitRow) {
break;
}
} else {
showText = connectShowText;
}
}
if (rowCount !== limitRow) {
context.fillText(showText, x, y);
}
var textHeightValue = rowCount < limitRow ? (textHeight + lineHeight): textHeight;
return textHeightValue;
}
这是示例,扫描访问二维码如下。
layer.alert方法内的文本需要换行就要加上换行而不是\n换行
layer.alert(‘需要换行的文字换行’)