出现的问题:swiper高度默认150px,swiper-item高度是100%,起初想让swiper-item中的内容吧swiper-item和其父元素高度撑开,理应将height设置成auto但是swiper的高度auto可以设置成功,但是swiper-item高度设置了auto始终是不成功(开发者工具中styles中显示出了但是就是不生效),
项目组件库使用的是u-view2.0,因为删除了u-view1.0中的tabswiper所以采取以下做法来实现
<view>
<swiper style="height: {{anchor.deviceHeight + 'px'}}" bindchange="swiperChange">
<swiper-item>
<view class="anchor-top"></view>
<!-- 你的内容 -->
<view class="anchor-bottom"></view>
</swiper-item>
<swiper-item>
<view class="anchor-top"></view>
<!-- 你的内容 -->
<view class="anchor-bottom"></view>
</swiper-item>
</swiper>
<view class="anchor-screen-bottom"></view>
</view>
data(){
returm{
anchor: {//处理swiper高度问题
deviceHeight: 0,
anchorTop: 0,
anchorBottom: 0,
anchorScreenBottom: 0
}
}
}
method:{
computeSwiperHeight(pageIndex) {
let getSwiperHeight = () => {
let min = this.anchor.anchorScreenBottom - this.anchor.anchorTop;
let value = this.anchor.anchorBottom - this.anchor.anchorTop
return Math.max(min, value)
}
wx.createSelectorQuery()
.select('.anchor-screen-bottom')
.boundingClientRect()
.selectViewport()
.scrollOffset()
.exec(res => {
this.anchor.anchorScreenBottom = res[0].bottom
})
wx.createSelectorQuery()
.selectAll('.anchor-top')
.boundingClientRect()
.selectViewport()
.scrollOffset()
.exec(res => {
this.anchor.anchorTop = res[0][pageIndex].top
this.anchor.deviceHeight = getSwiperHeight()
})
wx.createSelectorQuery()
.selectAll('.anchor-bottom')
.boundingClientRect()
.selectViewport()
.scrollOffset()
.exec(res => {
this.anchor.anchorBottom = res[0][pageIndex].bottom
this.anchor.deviceHeight = getSwiperHeight()
})
},
transition(e) {
this.currentNum = e.detail.current
console.log(e.detail.current, '-------')
this.computeSwiperHeight(e.detail.current)
},
}
.anchor-top {
width: 0;
height: 0;
}
.anchor-bottom {
width: 0;
height: 0;
}
.anchor-screen-bottom {
position: absolute;
bottom: 0;
width: 0;
height: 0;
}
原理:给 swiper-item 内部添加三个锚点,最上面一个,最下面一个,还有一个锚点始终位于屏幕最底下。根据这三个锚点计算出内容高度和内容显示区高度。 PS:锚点,宽高为 0 的不可见的 view,用于获取定位