[英]Resize an HTML element using touches
Using nothing more than the jQuery lib; 仅使用jQuery lib; I am trying to resize an
DIV
when dragging it's right border. 我正在尝试在拖动它的右边界时调整
DIV
大小。 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
. 我认为这与
e.touches
。
I have tryied using e.touches
and e.targetTouches
; 我试过使用
e.touches
和e.targetTouches
; none of them seem to work. 他们似乎都没有工作。
Am i implementing the touch events
part right ? 我是否正在实施
touch events
部分? What am i missing ? 我错过了什么?
Here is a fiddle , and the full code below. 这是一个小提琴 ,下面是完整的代码。
HTML: HTML:
<div class="container"><div class="handle"></div></div>
CSS: 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: 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
. 您应该使用
e.originalEvent.touches
而不是e.targetTouches
。
Allso it would help to have: 所以它有助于:
gesturechange
event alongside mousemove touchmove
mousemove touchmove
一起的gesturechange
事件 gestureend
event alongside mouseup touchend
mouseup touchend
一起的gestureend
事件 gesturestart
event alongside mousedown touchstart
gesturestart
一起事件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 . 另一个改进是在if语句中的文档mousemove事件回调移动
e.preventDefault()
,这样如果句柄为null,用户可以滚动页面。
I suffered with the same problem when doing a web application, and found this jquery touch plugin which solved my problem. 我在做一个Web应用程序时遇到了同样的问题,发现这个jquery touch插件解决了我的问题。
Download this plugin and include in ur html file and youre done. 下载此插件并包含在你的html文件中,你就完成了。 You dont need to call any touchstart/touchmove events .
你不需要调用任何touchstart / touchmove事件。
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. 为每个元素调用
addTouch()
方法,您需要响应触摸事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.