touchmoveが効かない
androidのタブレットでドラッグ的な事を実装しようと思い,touchstart, touchmove, touchend などのイベントをテストしていた所,ハマってしまったのでメモ。
上手く行かなかったソース
html
test
css
#test_box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 0px;
left: 0px;
}
#log {
position: fixed;
left: 600px;
top: 0px;
}
js
jQuery(function($){
var start_pageY, start_top;
$('#test_box').bind('touchstart', function(e){
start_pageY = e.originalEvent.touches[0].pageY;
start_top = $('#test_box').position().top;
loged('touchstart:pageY='+start_pageY+',top='+start_top);
});
$('#test_box').bind('touchmove', function(e){
var move_pageY = e.originalEvent.touches[0].pageY;
var move_top = start_top + move_pageY - start_pageY;
$('#test_box').css({top: move_top});
loged('touchmove:pageY='+move_pageY+',top='+start_top);
});
$('#test_box').bind('touchend', function(e){
var end_pageY = e.originalEvent.touches[0].pageY;
var end_top = $('#test_box').position().top;
loged('touchend:pageY='+end_pageY+',top='+end_top);
});
function loged(mes) {
$('#log').html($('#log').html() + '
' + mes);
return;
}
});
以上のソースでタブレット上でドラッグしようとしてもtouchmoveが終了してしまう。
上手く行ったソース
touchstartイベントをpreventDefault()してあげると上手く行くようだ。
テストの為にログを表示していたが,それをやっちゃうと重くなるので改良版では削除。
html と css は変更なし。
js
jQuery(function($){
var start_pageY, start_top;
$('#test_box').bind('touchstart', function(e){
start_pageY = e.originalEvent.touches[0].pageY;
start_top = $('#test_box').position().top;
e.preventDefault();
});
$('#test_box').bind('touchmove', function(e){
var move_pageY = e.originalEvent.touches[0].pageY;
var move_top = start_top + move_pageY - start_pageY;
$('#test_box').css({top: move_top});
});
$('#test_box').bind('touchend', function(e){
});
});
- 投稿タグ
- ajax, javascript

