简体   繁体   中英

Resize an HTML element using touches

Using nothing more than the jQuery lib; I am trying to resize an DIV when dragging it's right border. It works perfectly with a mouse but I can't make it work on a touch device. I think it's related to the e.touches .

I have tryied using e.touches and e.targetTouches ; none of them seem to work.

Am i implementing the touch events part right ? What am i missing ?

Here is a fiddle , and the full code below.

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();
    }
});

Any help would be appreciated!

Instead of e.targetTouches you should use e.originalEvent.touches .

Allso it would help to have:

  • gesturechange event alongside mousemove touchmove
  • gestureend event alongside mouseup touchend
  • gesturestart event alongside mousedown touchstart

Another improvement would be to on document mousemove event callback move e.preventDefault() in the if statement, that way the user can scroll the page if the handle is null .

I suffered with the same problem when doing a web application, and found this jquery touch plugin which solved my problem.

Download this plugin and include in ur html file and youre done. You dont need to call any touchstart/touchmove events .

If it doesn't work you can add the touch event like this :

$('Element').addTouch();

Call addTouch() method for every element, that you whant to respond to a touch event.

Check this link for more download options .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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