繁体   English   中英

使用触摸调整HTML元素的大小

[英]Resize an HTML element using touches

仅使用jQuery lib; 我正在尝试在拖动它的右边界时调整DIV大小。 它与鼠标完美配合,但我不能在触摸设备上工作。 我认为这与e.touches

我试过使用e.touchese.targetTouches ; 他们似乎都没有工作。

我是否正在实施touch events部分? 我错过了什么?

这是一个小提琴 ,下面是完整的代码。

HTML:

<div class="container"><div class="handle"></div></div>

CSS:

.container{background:#CCC;width:200px;height:100px;position:relative;overflow:hidden;}
.handle{cursor:e-resize;height:100px;width:2px;position:absolute;top:0;right:0;background:red;}

JS:

var handle = null;

$(".handle").on('mousedown touchstart', function(e){
    handle = {
        x : e.pageX,
        p : $(this).parent(),
        pw: $(this).parent().width()
    };

    if (e.targetTouches){ //e.touches
        handle.x = e.targetTouches[0].pageX //e.touches[0]
    }

    e.preventDefault();
});

$(document).on({
    'mousemove touchmove':function(e){
        if(handle) {
            if (e.targetTouches){ //e.touches
                handle.p.width(handle.pw+(e.targetTouches[0].pageX - handle.x));  //e.touches[0]               
            }else{
                handle.p.width(handle.pw+(e.pageX - handle.x));                    
            }
        }
        e.preventDefault();
    },
    'mouseup touchend':function(e){
        handle = null;
        e.preventDefault();
    }
});

任何帮助,将不胜感激!

您应该使用e.originalEvent.touches而不是e.targetTouches

所以它有助于:

  • mousemove touchmove一起的gesturechange事件
  • mouseup touchend一起的gestureend事件
  • gesturestart一起事件mousedown touchstart

另一个改进是在if语句中的文档mousemove事件回调移动e.preventDefault() ,这样如果句柄为null,用户可以滚动页面。

我在做一个Web应用程序时遇到了同样的问题,发现这个jquery touch插件解决了我的问题。

下载此插件并包含在你的html文件中,你就完成了。 你不需要调用任何touchstart / touchmove事件。

如果它不起作用,您可以添加如下触摸事件:

$('Element').addTouch();

为每个元素调用addTouch()方法,您需要响应触摸事件。

查看链接以获取更多下载选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM