美文网首页
uni-app之点击页面某元素,滚动到指定位置

uni-app之点击页面某元素,滚动到指定位置

作者: Cute_小肥鸡 | 来源:发表于2020-12-16 11:13 被阅读0次
<template>
  <view class="padding-top-xl" :class="'PTX_Ex_'+EL_item.id" v-for="(EL_item,EL_index) in NQL_item_1.ExList"></view>

  <view class="padding-xs">
    <view class="cu-avatar round margin-xs" v-for="(EL_item,EL_index) in NQL_item_1.ExList" @click="AppointedSubject" :data-id="EL_item.id">{{ EL_item.seq }}</view>
  </view>
</template>

<script>
    export default {
        data() {
            return {
                openAnswerSheetM: 0 //是否显示“题目序号”
            }
        },
        onLoad() {

        },
        methods: {
            AppointedSubject(e) { /////////////////////////////////////////////////////////////////////////////////题目序号 -- 点击某条题目的序号,跳转到指定题目
                //////////1、关闭题目序号的view,返回列表页面
                this.openAnswerSheetM = 0;
                //////////2、获取点击的习题ID
                var thisID = e.currentTarget.dataset.id;
                //////////3、点击某题目序号,滚动到某习题位置
                var timer = setTimeout(function() {
                    var scrollTop;
                    //3-1、获取某元素距离顶部的距离
                    var query = uni.createSelectorQuery();
                    query.select('.PTX_Ex_' + thisID).boundingClientRect(res => {
                        scrollTop = res.top;
                    }).exec()
                    //3-2、开始滚动
                    uni.pageScrollTo({
                        scrollTop: scrollTop,
                        duration: 300
                    });
                    //3-3、取消由 setTimeout() 方法设置的 timeout
                    clearTimeout(timer);
                }, 300);
            }
        }
    }
</script>

注意:uni.createSelectorQuery() 和 uni.pageScrollTo()要放在 setTimeout() 里面才能获取到值。

比如:点击第8题的序号,滚动到第8题


图1
图2

相关文章

网友评论

      本文标题:uni-app之点击页面某元素,滚动到指定位置

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