前言:
之前我写了一篇关于解决
cover-view
宽度无法自适应的文章,在解决完宽度自适应问题,又出现了其他问题…
项目场景:
微信小程序地图自定义气泡,虽然目前原生组件均已支持同层渲染,但是根据官网描述自定义气泡只能使用cover-view
。
问题描述
简单说下需求:要求是起终点地址描述最多7个字超出换行,真机效果如下图,模拟器展示没问题。
cover-view字体丢失、max-width不生效
解决方案:
1.cover-view字体丢失
wxml代码
<cover-view id="distanceViewParent" style="width: {{distanceViewWidth}};" class="c-ff6b mapview-marker-l">
<cover-view id="distanceView" style="width: {{distanceChildViewWidth}};" class="font-size-14 font-w-bold">
{{carTotal.distance}}公里
</cover-view>
<cover-view class="font-size-12 text-center" style="margin-top: 3rpx;">全程</cover-view>
</cover-view>
js文件代码
const {
getSelectorQuery
} = require('../../../common/global.js')
Page({
data:{
distanceViewWidth: 'auto', // 解决cover-view字体丢失问题
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
// 处理cover-view字体丢失
if (this.data.distanceViewWidth === 'auto') getSelectorQuery('distanceView', 'distanceViewParent', this)
}
})
global.js文件代码
/**
* 获取元素宽度
* @description 解决cover-view文字丢失问题
* @param {String} id 元素id
* @param {String} parentId 元素父级id
*/
let getSelectorQuery = function (id, parentId, that) {
let query = wx.createSelectorQuery()
query.select('#' + id).boundingClientRect()
query.select('#' + parentId).boundingClientRect()
query.exec(function(res){
let res0Width = Math.ceil(res[0].width)
let res1Width = Math.ceil(res[1].width)
let widthDiff = Math.ceil(res[0].width - res[1].width)
that.setData({
distanceViewWidth: (res1Width + (widthDiff > 0 ? widthDiff : 0) + 5) + 'px',
distanceChildViewWidth: (res0Width + 5) + 'px'
})
})
}
2.max-width不生效
首先在pages同级创建filter文件,filter文件下创建index.wxs
。
wxml代码
<!-- 引入过滤器 -->
<wxs module="f" src="../../../filter/index.wxs" />
<cover-view marker-id="1" bindtap="markerStart">
<cover-view class="mapview-marker">
<cover-view class="mapview-marker-r">
<cover-view
style="width: {{f.handleComputeWidth(startInfo.title)}};"
class="font-size-14 c-3333 font-w-bold mapview-marker-r-child"
>
{{startInfo.title}}
</cover-view>
</cover-view>
<cover-image class="ml-5 hw-12" src="{{rightSrc}}"/>
</cover-view>
</cover-view>
index.wxs代码
这里简单说一下
wxs
是微信小程序内置脚本语言,语法与js
是不尽相同的并且不识别ES6
及以上,全部用ES5
编写。
/**
* 根据字符串长度计算宽度
* @description 解决cover-view最大宽度不生效问题
* @param {String} str 字符串
* @returns
*/
var handleComputeWidth = function (strAddrss) {
var str = strAddrss || ''
var width = 0
if (str.length < 7) {
width = 28.6 * str.length
} else {
width = 200
}
return width + 'rpx'
}