微信小程序 实现自动换行

参考链接:
(1)微信小程序自动换行
https://blog.csdn.net/Hero_rong/article/details/100134634
(2)小程序 显示3个一排 自动换行
https://blog.csdn.net/fatong3/article/details/102903703

一、方法1:css word-break

word-break: break-all;
在需要换行的view上添加这个样式即可。
在这里插入图片描述
在这里插入图片描述

二、方法2:css width %

如显示3个一排。
使用的是width: 31%;

wxml文件
<!--3个一排,超过换行-->
<view class="link">
 <view class="link_child"> 1212 </view>
 <view class="link_child"> 1212 </view>
 <view class="link_child"> 1212 </view>
 <view class="link_child"> 1212 </view> 
</view>
wxss文件
.link {
 display: flex; flex-direction: row;
 flex-wrap: wrap; width: 654rpx;
 margin: 0 auto; position: relative;
 left: 5rpx; 
} 
.link_child {
 width: 31%;
 background: red;
 border: 1rpx solid black; 
} 
.link_child:not(:nth-child(3n)){
 margin-right: 10rpx; 
}

三、方法3:css width rpx

如显示3个一排。
使用的 width: 200rpx;(需要是3的倍数)

wxml文件
<view class="father"> 
 <view class="child test"> 1 </view>
 <view class="child test"> 2 </view>
 <view class="child test"> 3 </view>
 <view class="child test"> 4 </view>
 <view class="child test"> 5 </view>
 <view class="child test"> 6 </view> 
</view>
wxss文件
.test {
 border: 2rpx solid black; 
}
.father {
 width: 660rpx;
 display:flex;
 flex-wrap:wrap;
 justify-content:space-between; 
} 
.child{
 width: 200rpx; 
}
### 微信小程序中文字自动换行实现方法 #### 使用 CSS `word-break` 属性 对于简单的文本内容,可以通过设置 `word-break: break-all;` 来实现在指定区域内的自动换行。此属性允许单词内部断开以适应容器宽度[^1]。 ```css .text-container { word-break: break-all; } ``` #### 利用 Flexbox 布局配合 `flex-wrap` 另一种方式是通过定义父级元素为弹性盒子模型并启用其子项环绕功能来达成多列布局下的自然折行效果。具体表现为给定 `.agreement` 类名下的一系列视图组件能够按照设定间距排列成行列结构,在超出单行容纳限度时会自行转至下一行继续展示[^3]。 ```css .agreement { display: flex; flex-direction: row; padding-left: 30rpx; flex-wrap: wrap; /* 关键 */ align-content: space-around; } .agreement view { display: inline-block; /* 修改为 block-level element */ } ``` > **注意**: 这里将原本内联样式的 `<view>` 改为了块状显示 (`inline-block`) ,以便更好地控制每个项目的尺寸与间隔。 #### Canvas 绘制中的手动处理方案 当涉及到更复杂的场景比如在 canvas 上渲染带格式的文字串,则可能需要编程逻辑去计算每一行的最大容量,并据此分割原始字符串形成适合屏幕呈现的新段落列表[^2]。 ```javascript function drawTextOnCanvas(ctx, text, maxWidth) { const lines = []; let currentLine = ''; function checkWidth(str) { return ctx.measureText(str).width > maxWidth; } for (let i = 0; i < text.length; ++i) { if (!checkWidth(currentLine + text[i])) { currentLine += text[i]; } else { lines.push(currentLine); currentLine = text[i]; // Start new line with this character. } } if (currentLine !== '') lines.push(currentLine); return lines.map((line, index) => ({ yPosition: (index + 1) * lineHeight, content: line })); } ``` 上述代码片段展示了如何基于传入的内容和最大允许宽度动态调整输出到画布上的每一段话的位置信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值