在使用 uni-app
的 scroll-view
组件时,如果你希望在子节点 view
在可视区域显示 1/3 时点击该 view
节点能够触发 scroll-into-view
效果,但发现无法触发,可能是由于以下几个原因:
1. scroll-into-view
的使用方式
scroll-into-view
是 scroll-view
组件的一个属性,用于指定滚动到某个子元素的 ID。你需要确保以下几点:
- 每个子元素都有一个唯一的
id
属性。
scroll-into-view
属性的值应该是一个字符串,表示你想要滚动到的子元素的 id
。
<scroll-view scroll-into-view="{{scrollIntoId}}" scroll-y="true" style="height: 300px;">
<view id="item1" style="height: 100px;">Item 1</view>
<view id="item2" style="height: 100px;">Item 2</view>
<view id="item3" style="height: 100px;">Item 3</view>
</scroll-view>
export default {
data() {
return {
scrollIntoId: ''
}
},
methods: {
scrollToItem(id) {
this.scrollIntoId = id;
}
}
}
2. 点击事件的处理
你需要在点击 view
时,设置 scroll-into-view
的值为该 view
的 id
。
<scroll-view scroll-into-view="{{scrollIntoId}}" scroll-y="true" style="height: 300px;">
<view id="item1" style="height: 100px;" @tap="scrollToItem('item1')">Item 1</view>
<view id="item2" style="height: 100px;" @tap="scrollToItem('item2')">Item 2</view>
<view id="item3" style="height: 100px;" @tap="scrollToItem('item3')">Item 3</view>
</scroll-view>
3. 可视区域显示 1/3 的判断
如果你希望在 view
显示 1/3 时触发滚动,可能需要通过计算 view
在 scroll-view
中的位置来实现。你可以使用 uni.createSelectorQuery()
来获取 view
的位置信息,然后判断是否显示 1/3。
methods: {
scrollToItem(id) {
const query = uni.createSelectorQuery().in(this);
query.select(`#${id}`).boundingClientRect(data => {
if (data && data.top < this.scrollViewHeight / 3) {
this.scrollIntoId = id;
}
}).exec();
}
}
4. scroll-view
的高度
确保 scroll-view
的高度是固定的,否则可能会导致滚动行为不符合预期。
<scroll-view scroll-into-view="{{scrollIntoId}}" scroll-y="true" style="height: 300px;">
<!-- 子元素 -->
</scroll-view>
5. 其他可能的问题
- 确保
scroll-view
的 scroll-y
或 scroll-x
属性已经启用。
- 确保
scroll-into-view
的值是动态绑定的,并且在点击事件中正确更新。
示例代码
以下是一个完整的示例代码:
<template>
<view>
<scroll-view scroll-into-view="{{scrollIntoId}}" scroll-y="true" style="height: 300px;">
<view id="item1" style="height: 100px;" @tap="scrollToItem('item1')">Item 1</view>
<view id="item2" style="height: 100px;" @tap="scrollToItem('item2')">Item 2</view>
<view id="item3" style="height: 100px;" @tap="scrollToItem('item3')">Item 3</view>
</scroll-view>
</view>
</template>
<script>
export default {
data() {
return {
scrollIntoId: '',
scrollViewHeight: 300
}
},
methods: {
scrollToItem(id) {
const query = uni.createSelectorQuery().in(this);
query.select(`#${id}`).boundingClientRect(data => {
if (data && data.top < this.scrollViewHeight / 3) {
this.scrollIntoId = id;
}
}).exec();
}
}
}
</script>