【微信小程序】实现类似HTML中超级链接锚点跳转问题

先看一下效果展示:

在这里插入图片描述

主要用到 scroll-view 组件 scroll-into-view 属性;当点击导航菜单的时候,我们改变相应的 scroll-into-view 的值,并且同时需要在 scroll-view 组件内相应位置处的子元素上定义相应的 id;因为scroll-into-view 值应为某子元素 id,设置哪个方向可滚动,则在哪个方向滚动到该元素。

.wxml代码

<!--index.wxml-->
<view style="height:auto">
  <scroll-view class="tab-list" scroll-x="{{true}}" enable-flex='{{true}}'>
    <block wx:for='{{tabList}}' wx:key='tab'>
      <view class='tab-item' bindtap='onTabClick' data-index="{{index}}">
        <text class="tab-title{{tabIndex == index?' select':''}}">{{item.title}}</text>
      </view>
    </block>
  </scroll-view>
</view>
<view style="height:auto">
  <scroll-view style="height:100vh" scroll-y="{{true}}" scroll-into-view="{{tabItem}}" enable-flex="{{true}}"
    scroll-with-animation>
    <block wx:for="{{tabList}}" wx:key="index">
      <view id='tabItem-{{index}}' style="background-color:{{item.bgColor}};height:500rpx;">
        {{item.title}}
      </view>
    </block>
  </scroll-view>
</view>

.wxss代码

.tab-list {
  width: 100vw;
  height: 90rpx;
  white-space: nowrap;
  box-sizing: border-box;
  display: block;
  background: #fff;
  position: static;
  top: 0;
}

.tab-item {
  width: 18%;
  height: 90rpx;
  display: inline-block;
  white-space: normal;
  box-sizing: border-box;
  font-size: 28rpx;
  line-height: 90rpx;
  text-align: center;
  display: inline-block;
}

.tab-title {
  width: 100%;
  color: #333;
}

.tab-title.select {
  color: #00b7de;
}

.js代码

// index.js
let tabList = [{
    title: '第一',
    bgColor: '#FFFFE0'
  },
  {
    title: '第二',
    bgColor: '#C7A698'
  },
  {
    title: '第三',
    bgColor: '#00B26A'
  },
  {
    title: '第四',
    bgColor: '#0F8BDA'
  },
  {
    title: '第五',
    bgColor: '#BEDBE9'
  },
  {
    title: '第六',
    bgColor: '#FFCA28'
  }
]
Page({
  data: {
    tabList: tabList,
    tabIndex: 0,
    tabItem: ''
  },
  onTabClick(e) {
    let curTabIndex = e.currentTarget.dataset.index
    this.setData({
      tabIndex: curTabIndex,
      tabItem: 'tabItem-' + curTabIndex
    })
  }
})

注意点:

  • scroll-into-view 与子元素 id 不能以数字开头
  • scroll-with-animation属性:在设置滚动条位置时使用动画过渡;
  • 如果scroll-view占页面整个高度,可设置 scroll-view的高度 height:100vh , 设置height:100%无效

源代码下载地址: https://download.csdn.net/download/ah_biao/16418938.

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值