【问题标题】:How to make swipe function work dynamically on a table row?如何使滑动功能在表格行上动态工作?
【发布时间】:2016-02-16 07:12:44
【问题描述】:

我正在使用 Cordova 开发一个跨平台的移动应用程序。我有一个带有表格的 HTML 页面。我有一个按钮add row,单击时会在我的表中添加一个新行。我需要一个类似 iOS 的滑动操作来执行删除操作。我使用touchstart 事件在我的表格中滑动了一个静态行。这很好用,但不适用于动态创建的表行。这个滑动动作怎么做?

这是我目前的代码:

HTML

<div class="fortable">
    <table id="cashreg">
        <tr>
            <td class="tablecellbackground"><div class="del" id="d1" ><p>Delete</p></div><div id="cells" class="cells"><div class="denom"><p>Start Time</p></div><div class="cnt"><p>Select Item</p></div><div class="tots"><p>Employee</p></div><div class="tots1"><p>Price</p></div></div></td>
        </tr>
    </table>

    <input type="button" class="addmore">
</div>

JavaScript

在表格中添加一行:

$(".addmore").click(function(){
    var rows = $("#cashreg tr").length+1;
    $("#cashreg").append('<tr><td class="tablecellbackground"><div class="cells"><div class="denom"><p>Start Time</p></div><div class="cnt"><p>Select Item</p></div><div class="tots"><p>Employee</p></div><div class="tots1"><p>Price</p></div><div class="del"><p>Delete</p></div></div></td></tr>');
});

对于类似 iOS 的滑动:

window.addEventListener('load', function(){
    var el = document.getElementsByClassName('cells')[0];
    ontouch(el, function(evt, dir, phase, swipetype, distance){
        var touchreport = ''
        touchreport += '<b>Dir:</b> ' + dir + '<br />'
        touchreport += '<b>Phase:</b> ' + phase + '<br />'
        touchreport += '<b>Swipe Type:</b> ' + swipetype + '<br />'
        touchreport += '<b>Distance:</b> ' + distance + '<br />'
        if(dir=="left"){
            left=parseInt(($(".cells").css("top")).replace ( /[^\d.]/g, '' ))-distance;
            $(".cells").css("left","-"+left+"px")
        }
        if(dir=="right"){
            if($(".cells").css("left")== "-166px"){
                //left=parseInt(($(".cells").css("top")).replace ( /[^\d.]/g, '' ))-distance;
                $(".cells").css("left","0px")
            }
        }
        if(dir=="none"){
            // document.getElementById("hi").value=el.pageX;
        }
    })
}, false)

function ontouch(el, callback){
    var touchsurface = el,
    dir,
    swipeType,
    startX,
    startY,
    distX,
    distY,
    threshold = 50, //required min distance traveled to be considered swipe
    restraint = 100, // maximum distance allowed at the same time in perpendicular direction
    allowedTime = 500, // maximum time allowed to travel that distance
    elapsedTime,
    startTime,
    handletouch = callback || function(evt, dir, phase, swipetype, distance){}

    touchsurface.addEventListener('touchstart', function(e){
        var touchobj = e.changedTouches[0]
        dir = 'none'
        swipeType = 'none'
        dist = 0
        startX = touchobj.pageX
        startY = touchobj.pageY
        startTime = new Date().getTime() // record time when finger first makes contact with surface
        handletouch(e, 'none', 'start', swipeType, 0) // fire callback function with params dir="none", phase="start", swipetype="none" etc
        e.preventDefault()
    }, false)

    touchsurface.addEventListener('touchmove', function(e){
        var touchobj = e.changedTouches[0]
        distX = touchobj.pageX - startX // get horizontal dist traveled by finger while in contact with surface
        distY = touchobj.pageY - startY // get vertical dist traveled by finger while in contact with surface
        if (Math.abs(distX) > Math.abs(distY)){ // if distance traveled horizontally is greater than vertically, consider this a horizontal movement
            dir = (distX < 0)? 'left' : 'right'
            handletouch(e, dir, 'move', swipeType, distX) // fire callback function with params dir="left|right", phase="move", swipetype="none" etc
        }
        else{ // else consider this a vertical movement
            dir = (distY < 0)? 'up' : 'down'
            handletouch(e, dir, 'move', swipeType, distY) // fire callback function with params dir="up|down", phase="move", swipetype="none" etc
        }
        e.preventDefault()
        // prevent scrolling when inside DIV
    }, false)

    touchsurface.addEventListener('touchend', function(e){
        var touchobj = e.changedTouches[0]
        distX = touchobj.pageX - startX
        elapsedTime = new Date().getTime() - startTime // get time elapsed
        if (elapsedTime <= allowedTime){ // first condition for awipe met
            if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint){ // 2nd condition for horizontal swipe met
                swipeType = dir // set swipeType to either "left" or "right"
            }
            else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint){ // 2nd condition for vertical swipe met
                swipeType = dir // set swipeType to either "top" or "down"
            }
        }
        // Fire callback function with params dir="left|right|up|down", phase="end", swipetype=dir etc:
        handletouch(e, dir, 'end', swipeType, (dir =='left' || dir =='right')? distX : distY)
        e.preventDefault()
        if(dir=="left"){
            if(distX>-100){
                $(".cells").css("left","0px")
            }
            else if(distX<-50 && distX>-100){
                $(".cells").css("left","-166px")
            }
            else{
                $(".cells").css("left","-166px")
            }
        }
    }, false)
}

如何使这种滑动应用于新添加的表格行?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    你应该使用事件委托on()来处理js动态添加的新元素:

    $("body").on('touchstart click','#cashreg tr', function(e){
    
    })
    

    希望这会有所帮助。

    【讨论】:

    • 但是在哪里有这个函数(evt、dir、phase、swipetype、distance)事件呢?你能解释一下怎么做吗?@Zakaria Acharki
    【解决方案2】:

    问题在于您将单元格元素与load 函数中的事件ontouch 绑定在一起。这意味着只有加载时存在的元素才会被绑定。您还需要在新创建的行元素上注册ontouch 事件。

    通过您的示例,您可以尝试直接使用ontouch html 属性,即:

     <div class="cells" ontouchstart="...">
    

    或简单地将触摸事件绑定到您的身体并检查处理程序中的cells 类:

     var el = document.getElementsByTagName('body')[0];
     ontouch(el, function(evt, dir, phase, swipetype, distance){
         if($(evt.target).hasClass("cells")){
             // your code
         }
     }); 
    

    【讨论】:

    • 谢谢 但是怎么绑定呢?你能帮我编码吗?@Shitsu
    • 我的错。编辑了答案。
    • 我找不到你。能否请您发送代码sn-p。或者用简单的方式解释我? @Shitsu
    • 第二个 sn-p 只是加载函数的第一行,但有一些修改(绑定到 body 和 if)。第一个与onclick="function()" 完全一样。什么不清楚?
    • 我尝试了第一个功能。 ontouchstart="ontouch(this)", 它是动态工作的,但工作速度较慢。为什么?
    猜你喜欢
    • 2023-04-02
    • 2016-09-20
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    相关资源
    最近更新 更多