Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

如何优化translate3d模拟滚动条

现在按照网上的用translate3d完成了模拟滚动,但是滚动效果很痛苦,不知应该如何优化,才能像scroll那样做到正常滑动啊?现所用模拟代码如下:

var gundongX = 0;
var gundongY = 0;
var d = document;
var g = 'getElementById';
var moveEle = d[g]('scroller');

var stx = sty = etx = ety = curX = curY = 0;

moveEle.addEventListener("touchstart", function(event) { //touchstart
    gundongX = 0;
    gundongY = 0;


    // 元素当前位置
    etx = parseInt(getT3d(moveEle, "x"));
    ety = parseInt(getT3d(moveEle, "y"));

    // 手指位置
    stx = event.touches[0].pageX;
    sty = event.touches[0].pageY;
}, false);

moveEle.addEventListener("touchmove", function(event) {
    // 防止拖动页面
    event.preventDefault();

    // 手指位置 减去 元素当前位置 就是 要移动的距离
    gundongX = event.touches[0].pageX - stx;
    gundongY = event.touches[0].pageY - sty;

    // 目标位置 就是 要移动的距离 加上 元素当前位置
    curX = gundongX + etx;
    curY = gundongY + ety;
    if(curY>0){
        curY = 0;
    } else if(curY<=window.innerHeight-todObj.sousuoTopObj.pageHeight){
    //到达底部,下拉刷新
        curY = window.innerHeight-todObj.sousuoTopObj.pageHeight;
        if(todObj.indexPageObj.pageNum == 2){
                
                if(todObj.indexPageObj.slide_type==1){
                    if( (todObj.indexPageObj.currentpage<todObj.indexPageObj.totalPage&&(todObj.indexPageObj.totalPage!=-1)||todObj.indexPageObj.totalPage==-1)){
                        
                        if(todObj.indexPageObj.isAjax){
                            todObj.indexPageObj.currentpage++;
                            p2_index_pul();    
                        }
                        
                    }
                }
                }
    }

    // 自由移动
    // moveEle.style.webkitTransform = 'translate3d(' + (curX) + 'px, ' + (curY) + 'px,0px)';
    // 只能移动Y轴方向
    moveEle.style.webkitTransform = 'translate3d(' + 0 + 'px, ' + (curY) + 'px,0px)';


}, false);
moveEle.addEventListener("touchend", function(event) { //touchend
    etx = curX;
    ety = curY;
}, false);

function getT3d(elem, ename) {
    var str1 = elem.style.webkitTransform;
    if (str1 == "") return "0";
    str1 = str1.replace("translate3d(", "");
    str1 = str1.replace(")", "");
    var carr = str1.split(",");

    if (ename == "x") return carr[0];
    else if (ename == "y") return carr[1];
    else if (ename == "z") return carr[2];
    else return "";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

可以加上 transition 属性优化效果还可以加上缓动函数优化性能。还想进一步优化,你可以看看 iScroll 的源码学习学习


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...