小程序scroll-view 实现大图滚动显示总结

有一张大图宽度较大, 一个屏幕展示不开, 需要自动滚动

scrollview显示 wxml

 <scroll-view  scroll-x="true" style="height: {{imageHistoryRect.height}};" bindscrolltoupper="upper"
                 bindscrolltolower="onToLower"
                 bindscroll="onScroll" scroll-left="{{scrollLeft}}">
        <image bindload="onImageLoad" style="width:{{ imageHistoryRect.width }}px; height:{{ imageHistoryRect.height }}px;"
               src="http://kookong.com/static/img/aboutme.png"></image>
    </scroll-view>

js中获取图片真实宽高, 并设置奥scroll-view和image

 onImageLoad: function (e) {
        var $width = e.detail.width,    //获取图片真实宽度
            $height = e.detail.height,
            ratio = $width / $height;    //图片的真实宽高比例
        var viewWidth = 718,           //设置图片显示宽度,左右留有16rpx边距
            viewHeight = 718 / ratio;    //计算的高度值
        console.log(TAG, viewWidth)
        console.log(TAG, viewHeight)
        this.setData({
            imageHistoryRect: {
                width: viewWidth,
                height: viewHeight
            }
        })
    },
onToLower: function (e) {//scrollview滑动到底部的时候停止timer
    clearInterval(this.timer)
    console.log(TAG, "onToLower" + e.detail)
    // this.setData({ //也可以从开头重新滑动
    //     scrollLeft: 0
    // })
},
onScroll: function (e) { //只是打印scroll-view滑动事件, 用来调试
    console.log(TAG, "onScroll:scrollLeft:" + e.detail.scrollLeft)
},
onShow: function () { //在Page显示的时候 启动timer. 可以直接this.timer赋值,不用声明
    this.timer = setInterval(this.scrollHistoryView, 60)
    console.log(TAG, "setInterval")
},
onHide: function () { //在Page隐藏的时候, 关闭timer
    clearInterval(this.timer)
    console.log(TAG, "clearInterval")
},
scrollHistoryView: function () { //自动滚动scroll-view代码
    // console.log(TAG, "scrollHistoryView:" + this.data.scrollLeft),
        this.setData({
            scrollLeft: this.data.scrollLeft + 7
        })
},

数据定义

data: {
    scrollLeft: 0,
    imageHistoryRect: {}}

其间遇到一个问题, scroll-view不能自动滚动到底部 将scroll-with-animation="true" 去掉就好了

这篇文章的同学似乎说的不对 https://blog.csdn.net/TrZoey/article/details/79914168

参考

小程序的settimeout和setinterval: https://blog.csdn.net/xuexixuexien/article/details/79146659

微信小程序image图片自适应宽度比例显示的方法: http://www.qianduan8.com/1005.html

微信小程序scroll-view无法准确滚动到页面最底部 https://blog.csdn.net/TrZoey/article/details/79914168

猜你喜欢

转载自my.oschina.net/sfshine/blog/1797754