簡體   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