uniapp锚点定位
uniapp 锚点定位
·
uniapp 锚点定位
需求:在 uniapp 写 App 时,根据后端接口返回的数据渲染图文,并且要对图片进行锚点定位。
前提:后端要给每张图片一个单独的参数,用来区分每张图片。
思路:前端将这个特定参数注入到图片标签中,并且根据此特定参数进行锚点定位。
疑问:怎么用 uniapp 在 App 中进行锚点定位呢?
方法:用 uniapp 的 scroll-view 的 scroll-into-view
属性进行锚点定位。
scroll-view 标签必须给高度,不然在 App 中无法滚动,进而实现不了锚点定位效果。
(我的页面是后端返回的数据,高度不固定,因此不能写死高度。因此我将<scroll-view> </scroll-view>
包裹住整个页面,再给一个页面高度 100vh ,就解决了高度问题。)
代码:
<template>
<view>
<!-- #ifndef H5 -->
<scroll-view class="scroller" :scroll-into-view="toView" scroll-y="true" scroll-with-animation="true">
<!-- #endif -->
<view class="parseContainer" v-for="item in contentList" :key="item.id">
<view v-for="item1 in item.contents" :key="item1.id">
<!-- 需要锚点定位的图片: -->
<image v-for="(item2, index2) in item1.coverImgs.split(',')" :key="index2" style="width: 100%" mode="widthFix" :src="item2" :id="'anchor'+item1.imgList[0].id"></image>
<text class="word">{{ item1.content }}</text>
</view>
</view>
<!-- #ifndef H5 -->
</scroll-view>
<!-- #endif -->
</view>
</template>
export default {
data() {
return {
toView:'',
}
},
methods: {
toAnchor(id) {
let anchorId = 'anchor'+id
// #ifdef H5
document.documentElement.scrollTop = document.getElementById(anchorId).offsetTop - 100
// #endif
// #ifndef H5
this.toView = anchorId;
// #endif
}
}
}
以上代码中
#ifdef H5
、#ifndef H5
、#endif
均为 条件编译 ,因为在 H5 中锚点定位简单得很,不用这么复杂,所以单独用别的方法来处理。
番外:
也尝试过用以下 uni.pageScrollTo()
来做锚点定位,但是我这边 会出现 Bug: 同一个元素多次触发锚点次定位时,无法定位到准确位置…
let anchorId = 'anchor'+id
// #ifdef H5
document.documentElement.scrollTop = document.getElementById(anchorId).offsetTop - 100
// #endif
// #ifndef H5
uni.createSelectorQuery().select(`.${anchorId}`).boundingClientRect(data => {
// 此处的定时器,目的是:等待页面渲染完,然后滚动页面
this.$nextTick(() => {
uni.pageScrollTo({
scrollTop: data.top,
})
})
}).exec();
// #endif
更多推荐
已为社区贡献2条内容
所有评论(0)