uni-app 完美支持安卓和ios 的 js 图片跟着滚动条滚动

<template>
    <div class="content" ref="con">
        <img ref="dd" class="directory_bg" src="../../static/image/directory/directory_bg.png" />
		<scroll-view class="directory_list" scroll-y @scroll='soll'>
			<view class="" v-for="(item,index) in 82" :key="index" style="height: 100px;">
				{{item}}--{{index}}
			</view>
		</scroll-view>
    </div>
</template>

<script>
export default {
    data(){
        return {
			imgH:0,
			listH: 0,
			conH: 0
        }  
    },
	onReady() {
		this.getInfo()
	},
	mounted(){
		// console.log(this.$refs.dd.offsetHeight ,this.$refs.con.offsetHeight)
		// this.imgH = this.$refs.dd.offsetHeight - this.$refs.con.offsetHeight; //计算溢出高度
		this.conH = this.$refs.con.offsetHeight;
	},
	methods:{
		soll(event){
			console.log(event)
			if(!this.imgH && this.$refs.dd.offsetHeight) {
				this.imgH = this.$refs.dd.offsetHeight - this.conH;
			}
			 event.preventDefault()
			const {scrollHeight, deltaY, scrollTop} = event.detail;
			// 
			/**
			 * 
			 * (图片溢出的高) =  图片总高度- 视图高度
			 * (总的滚动条距离顶部距离) = (滑到最底部的时滚动条距离顶部的距离) = (总的列表高度 - 可视区域的高度)
			 * 当前滑动的位置滚动条距离顶部的占比 = (图片溢出的高 / (总的滚动条距离顶部距离))
			 * 当前scrollTop(当前滚动条距离顶部的高度) * (图片溢出的高 / (总的滚动条距离顶部距离))
			 */
			 //计算公式
			this.$refs.dd.style.marginTop = -(scrollTop * (this.imgH / (scrollHeight - this.$refs.con.offsetHeight))) +'px'
		},
		getInfo(){
		}
	}
}
</script>

<style lang='less' scoped>
.content{
	height: 100vh;
	overflow: hidden;
	.directory_bg{
		margin-top: 0;
		width: 100%;
		transition: .1s;
	}
	.directory_list{
		position: absolute;
		z-index: 1;
		top: 0;
		height: 100%;
	}
}
</style>

你可能感兴趣的:(uniapp,javascript,uni-app,前端)