使用touchmove的Javascript +阈值?

时间:2013-01-21 22:05:59

标签: javascript threshold touchstart touchmove

我写了一个非常简单的脚本,允许用户滚动省略号文本。它使用touchstart和touchmove事件来擦除文本。除了我向可滚动文本添加阈值时,它工作正常。基本上,阈值使文本绑定到文本容器的宽度,不多也不少。然而不幸的是,滚动动作朝向阈值变得不可预测,而不是在它应该的位置结束而不是平滑地移动(100%的时间)。当我删除阈值时,文本从前到后平滑滚动。任何人都可以建议一个更好的方法来写一个门槛吗?

示例:http://one2mm.com/scrolling_text/

HTML:

<body onload="checkOverFlow()">
   <div class="m_header">
      <div id="header" class="ellipsis">a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z</div>
   </div>
</body>

JS:

function checkOverFlow(){
    var ellipsis = document.getElementsByClassName('ellipsis');
    for (var i = 0; i < ellipsis.length; i++){
        scrollEllipsis(ellipsis[i]);
    }
}

function scrollEllipsis(obj) {
    var objContainerWidth = obj.parentNode.offsetWidth;
    var text = obj.childNodes[0].data;
    var id = 'temp_'+obj.id;
    var tmpDiv = document.createElement('div');
    tmpDiv.setAttribute('id', id);
    obj.parentNode.appendChild(tmpDiv);
    var tmpObj = document.getElementById(id);
    tmpObj.innerHTML = text;
    var objTextWidth = tmpObj.offsetWidth;
    obj.parentNode.removeChild(tmpDiv);
    var overlap = (objTextWidth - objContainerWidth);

    var origin = 0;
    var marginLeft = 0;
    var currentX = 0;
    obj.style.marginLeft = '0px';

    if(objTextWidth > objContainerWidth) {
        obj.style.cursor = 'ew-resize';

        //start
        obj.addEventListener('touchstart', function(event) {
            event.preventDefault();
            origin = event.touches[0].pageX;
            marginLeft = parseInt(obj.style.marginLeft, 10);    
        }, false);

        //move
        obj.addEventListener('touchmove', function(event) {
            event.preventDefault();
            currentX = event.touches[0].pageX - origin + marginLeft;
            //threshold conditional             
            if(currentX < 0 && currentX >= -overlap) 
                obj.style.marginLeft = currentX+"px";
        }, false);      
    }
}

0 个答案:

没有答案