网络编程 
首页 > 网络编程 > 浏览文章

微信小程序点击item使之滚动到屏幕中间位置

(编辑:jimmy 日期: 2024/12/25 浏览:3 次 )

1.需求

微信小程序点击item使之滚动到屏幕中间位置

想做类似猫眼电影选场次会自动滚动到屏幕中间的效果

如图是最终效果 

2.分析

实现这种效果的方法有三种:

1.直接使用原生CSS+js;

2.使用swiper,一屏显示多个item,点击item会自动滚动到中间

3.使用微信的scroll-view配合JS实现

权衡了一下最终选择了第三个方案,比较是微信自带的方法,使用起来会比较流畅,swiper的话会比较臃肿,原生的话就比较麻烦,需要考虑的兼容问题比较多。

3.代码

wxml

<view class="items-box">
  <scroll-view class="scroll-view_H" scroll-x="true" style="width: 100%" bindscroll="scrollMove" scroll-left='{{scrollLeft}}' scroll-with-animation="true">
  <view class="scroll-wrapper">
   <view id="scroll-item-{{index}}" class="item-pic {{selectItemIndex==index" wx:for="{{ticketDetails}}" wx:key="index" bindtap="selectItem" data-index="{{index}}" data-name="{{item.TicketTitle}}" data-ticketid='{{item.TicketId}}'>
   <image src='{{imgUrl}}{{item.TicketPostImg}}'></image>
   </view>
  </view>
  </scroll-view>
</view>
<view class="item-name" hidden="{{!selectItemName}}">{{selectItemName}}</view>

wxss

.items-box .item-pic image {
 width: 90rpx;
 height: 120rpx;
}
 
.items-box .item-pic.on image {
 width: 110rpx;
 height: 148rpx;
 border: 4rpx solid #2bb7b3;
 box-sizing: border-box;
}
 
.items-box .item-pic {
 margin: 0 20rpx;
}
.items-box .item-pic:first-child{
 padding-left: 300rpx
}
.items-box .item-pic:last-child{
 padding-right: 300rpx
}
.item-name {
 padding: 18rpx 0;
 background-color: #fff;
 font-size: 24rpx;
 font-weight: 500;
 color: #232324;
 text-align: center;
}
 
.items-box .scroll-wrapper {
 align-items: flex-end;
 padding: 32rpx 0 0 0;
}
 
.items-box .scroll-view_H {
 border: none;
 background-color: #edeff1;
}

js

data:{
 moveParams: {
  scrollLeft: 0
 }
} 
 
getRect(ele) { 
//获取点击元素的信息,ele为传入的id
 var that = this;
 //节点查询
 wx.createSelectorQuery().select(ele).boundingClientRect(function (rect) {
  console.log(rect)
  let moveParams = that.data.moveParams;
  moveParams.subLeft = rect.left;
  moveParams.subHalfWidth = rect.width / 2;
  that.moveTo();
 }).exec()
 },
 moveTo: function () {
 let subLeft = this.data.moveParams.subLeft;
 let screenHalfWidth = this.data.moveParams.screenHalfWidth;
 let subHalfWidth = this.data.moveParams.subHalfWidth;
 let scrollLeft = this.data.moveParams.scrollLeft;
 
 let distance = subLeft - screenHalfWidth + subHalfWidth;
 
 scrollLeft = scrollLeft + distance;
 
 this.setData({
  scrollLeft: scrollLeft
 })
 },
 scrollMove(e) {
 let moveParams = this.data.moveParams;
 moveParams.scrollLeft = e.detail.scrollLeft;
 this.setData({
  moveParams: moveParams
 })
 },
 //选择项目
 selectItem: function (e) {
 let ele = 'scroll-item-' + e.currentTarget.dataset.index
 this.getRect('#' + ele);
 },

首先获取屏幕的宽度,再获取点击元素的宽度,计算一下就可以获得应该滚动的距离,再更改scroll-left='{{scrollLeft}}'即可

微信获取元素宽高的方法

wx.createSelectorQuery().select(ele).boundingClientRect(function (rect) {

}).exec()

https://developers.weixin.qq.com/miniprogram/dev/api/wxml/wx.createSelectorQuery.html

总结

上一篇:微信小程序scroll-view隐藏滚动条的方法详解
下一篇:微信小程序scroll-view点击项自动居中效果的实现