本文实例为大家分享了微信小程序实现轮播图标题跑马灯的具体代码,供大家参考,具体内容如下
微信小程序做轮播图,轮播图下的标题如果不长不需要跑马灯效果,过长的无法显示全的则添加跑马灯效果
<swiper class="swiper" current="0" bindchange="onSlideChange">
<swiper-item wx:for='{{carouselImgArr}}' wx:key='index'>
<image
src='{{item.image}}'
mode='heightFix'
class="swiper-item-img">
</image>
<view class="swiper-item-tit" wx:if='{{item.title}}'>
<view class="swiper-tit-inner {{(currImgIndex - 1) == index ? 'active' : ''}}"
style='transform:translate({{ ((currImgIndex - 1) == index ? carouselTitLeft : 0) + "px" }})'>
{{item.title}}
</view>
</view>
</swiper-item>
</swiper>
.swiper{
position: relative;
height: 430rpx;
padding: 0px;
margin: 0px;
}
.swiper image{
height: 430rpx;
position: absolute;
left:50%;
top:50%;
transform: translate(-50%,-50%);
}
.swiper-item-tit{
position: absolute;
bottom: 0rpx;
left:0rpx;
z-index: 2;
height: 80rpx;
line-height: 80rpx;
color:#fff;
width:100%;
/* overflow: hidden; */
/* text-overflow: ellipsis; */
background-color: rgba(0,0,0,0.5);
}
.swiper-item-tit .swiper-tit-inner{
text-align: center;
white-space: nowrap;
}
data: {
carouselImgArr: [{
image:'../../image/1.png',title:'标题',
},{
image:'../../image/1.png',title:'标题标题标题标题标题标题标题标题标题',
},{
image:'../../image/1.png',title:'标题',
} ],
carouselTitleLength:[2,18,2],// 轮播图标题的文字长度
carouselTitLeft:0,
currImgIndex: 1,
windowWidth: wx.getSystemInfoSync().windowWidth
},
onSlideChange(e) {
this.setData({
currImgIndex: e.detail.current + 1,
carouselTitLeft: 0
});
this.initMarqueen();
},
initMarqueen() {
clearInterval(marqueenTimer);
var self = this;
var boxWidth,textWidth;
var query = wx.createSelectorQuery();
// query.select('.swiper-item-tit').fields({size:true},function(res){
// boxWidth = res.width;
// }).exec();
// query.select('.active').fields({size:true},function(res){
// textWidth = res.width;
// }).exec();
setTimeout(function(){
let boxWidth = self.data.windowWidth;// 屏幕尺寸宽等于字体box宽,所以这里用屏幕宽替代了query获取的宽
let scale = boxWidth / 375;// 以屏幕尺寸为375为标准(375下字体宽约为14),根据屏幕尺寸计算单个字体的宽度
// 不知道为什么用query 获取的textWidth始终等于boxWidth的宽度,不得已只能使用文字长度乘以文字宽度来计算boxWidth。而
let textWidth = self.data.carouselTitleLength[self.data.currImgIndex - 1] * (14*scale);
console.log(scale,boxWidth,textWidth);
if (textWidth - 3*scale > boxWidth) {// 减去3*scale防止textWidth只多出来一点点导致文字左右震荡
let stayTime = 1000;
let endStay = true;
marqueenTimer = setInterval(function(){
let currLeft = self.data.carouselTitLeft;
if (stayTime !== 0) {
stayTime = stayTime - 30;
console.log('stay')
} else if (currLeft > boxWidth - textWidth) {
self.setData({
carouselTitLeft: currLeft - 2
});
} else {
if (endStay) {// 跑马灯结尾停留1s;
endStay = false;
stayTime = 1200;
return;
}
self.setData({
carouselTitLeft: 0
});
stayTime = 1200;// 回到跑马灯开头再停留1s;
endStay = true;
}
},100)
}
},100);
},