美文网首页
【微信小程序】实现锚点跳转

【微信小程序】实现锚点跳转

作者: 北极星丶超帅的 | 来源:发表于2018-03-13 16:42 被阅读1497次

    在微信小程序中想用a标签来进行锚点跳转却没有起作用,最后用scrollTop解决

    WXML

    <!-- 锚点跳转的view start-->
    <scroll-view scroll-y="true"  scroll-top="{{scrollTop}}" >
      <view class="self_row r1">1</view>
      <view class="self_row r2">2</view>
      <view class="self_row r3">3</view>
      <view class="self_row r4">4</view>
      <view class="self_row r5">5</view>
    </scroll-view>
    <!-- 锚点跳转的view end-->
    <!-- 右边导航栏 start-->
    <view class='right_nav'>
        <view wx:for="{{rightNav}}" wx:key="index" class='nav_item' data-id="{{item.id}}" bindtap="setScrollTop">
         <text class='item_name'>{{item.name}}</text>
        </view>
    </view>
    <!-- 右边导航栏 end-->
    

    JS

    Page({
      data: {
        rightNav:[
          { id: "1", name:"世"},
          { id: "2", name: "界" },
          { id: "3", name: "你" },
          { id: "4", name: "好" },
          { id: "5", name: "吗" }
        ],
        scrollTop: 0     //滚动的值
      },
      //右边导航栏锚点跳转
      setScrollTop: function(e) {
        //将rpx转化为px
        var p = 750 / this.data.winWidth;
        //获取当前点击的id值
        var showId = e.currentTarget.dataset.id;
        var scrollTop = 0;
        var len = rightNav.length+1;
        for(var i=0;i<len;i++){
          //当前的点击的id值等于i的话执行scrollTop滚动
          if (i==showId){
            //600是点击导航栏对应的元素的高度,scrollTop 滚动的高度
            scrollTop = ( 600 * (i - 1) ) / p;
          }
        }
        this.setData({
          scrollTop: scrollTop
        })
      },
      onLoad: function () {
        // 获取屏幕的高度
        var sysInfo = wx.getSystemInfoSync();
        var winHeight = sysInfo.windowHeight;
        var winWidth = sysInfo.windowWidth; 
        this.setData({
          winHeight: winHeight,
          winWidth: winWidth
        })
      }
    })
    

    相关文章

      网友评论

          本文标题:【微信小程序】实现锚点跳转

          本文链接:https://www.haomeiwen.com/subject/ocbzfftx.html