使用touchmove / mousemove时,左侧位置不准确()

时间:2014-05-15 08:01:45

标签: javascript jquery

我一直在开发一个侧边栏,应该允许用户拖动绿色标签以展开和折叠侧边栏。我相信它主要存在,但是当拖动侧边栏时,用户会遇到一些阻力,因为我认为这是不准确的位置()。左值。

如果你将CSS侧面板上的过渡时间减少到5ms,那么面板跳跃会更明显。

var sidebar = (function(){

    var $document = $(document),
        $panel = $('#side-panel'),
        $tab = $panel.find('.btn'),
        panelWidth = $panel.width(),
        lastPanelPos = 0,
        panelOpen = false,
        hasTouch = false;

    var eventTypes = {
        eventStart: "mousedown",
        eventEnd: "mouseup",
        eventMove: "mousemove"
    };

    if($('html').hasClass('touch')){   

        hasTouch = true;

        eventTypes = {
            eventStart: "touchstart",
            eventEnd: "touchend",
            eventMove: "touchmove"
        };
    }

    // Tab drag starts
    function startDrag(){

        panelOpen = !panelOpen;

        $panel.bind(eventTypes.eventMove, changePanelPosition); 
    }

    // Tab drag finishes
    function dragEnd(){

            $panel.unbind(eventTypes.eventMove); 

            if(panelOpen){
                $panel.css("-webkit-transform", "translateX("+panelWidth+"px)");
            }else{
                $panel.css("-webkit-transform", "translateX(0px)");
            }
    }

    // Drag side panel
    function changePanelPosition(event){

        // Prevent android from cancelling touchmove event
        event.preventDefault();

        var parentOffset = $panel.position(),
            pageX = (hasTouch) ? event.originalEvent.touches[0].pageX :  event.originalEvent.pageX,
            relX = pageX - parentOffset.left;

        if(relX < 0){
            relX = 0; 
        }else if(relX > panelWidth){
            relX = panelWidth;       
        }

        $panel.css("-webkit-transform", "translateX("+relX+"px)");

        lastPanelPos = relX;
    }

    // Events
    $tab.on(eventTypes.eventStart, startDrag);
    $document.on(eventTypes.eventEnd, dragEnd);
}());



<div id="side-panel">
    <div class="btn"></div>
</div>

链接到 js fiddle

1 个答案:

答案 0 :(得分:0)

我不需要在每次鼠标移动时计算$panel.position().left,所以我只是将其移动到函数的顶部。或许可以解决这个问题,但现在似乎还不错: LINK