您的位置:首页 > 其它

移动触摸屏的div拖动Demo

2012-05-26 16:51 141 查看
话说我刚刚从PC的Web开发转到移动的Web开发……

当前移动Web开发不得不面对强大的流行的Android,IOS这两大触摸屏系统啊,毕竟这是热门啊,用户都在这里。

这次因为开发需要,我得试着做一个背景可以拖动的div页面。当一切都在PC上做完之后,转到手机进行测试,竟然无效啊,拖动无效。经过调试发现mousemove事件(还有mousedown,mouseup)的clientX的属性在PC端几款浏览器都没问题,在平板的Android浏览器和QQ浏览器下都是未定义undefined。

当时想是不是因为event.clientX在移动端不支持,然后就试了一下offsetXscreenX,结果都一样,这个时候都快崩溃了我。

按说mousedown,mouseup,mousemove和touchstart,touchend,touchmove之间是可以互通的,也就是说一般面向pc开发的mouse时间对touch事件有效,据说是效率有差异。但是pc上测试没有任何问题,在手机上就是无效。

然后百度了很久很久……

终于在一个讨论touch相关事件的例子中看到别人已经经过测试的e.touches[0].pageX,光这个属性还是不够的,发现使用jquery为div绑定touch事件后这个属性也是未定义,必须使用原生的addEventListener。

最后,贴上demo的代码,希望给遇到同样问题的你提供帮助。

<html>
<head>
<meta charset="UTF-8">
<style type="text/Css">
body{background-color:#000000;}
.window{position:absolute;z-index:1;overflow:hidden;width:600px;height:400px;background-color:red;left: 0px;}
.dragme{position:relative;background-image:url('img/testbg.png');width:800px;height:400px;}
</style>

<script type="text/javascript" charset="utf-8" src="js/jquery.min.js"></script>
<script type="text/javascript">
var isdrag=false;
var tx,x;
$(function(){
document.getElementById("moveid").addEventListener('touchend',function(){
sdrag = false;
});
document.getElementById("moveid").addEventListener('touchstart',selectmouse);
document.getElementById("moveid").addEventListener('touchmove',movemouse);
});
function movemouse(e){
if (isdrag){
var n = tx + e.touches[0].pageX - x;
$("#moveid").css("left",n);
return false;
}
}

function selectmouse(e){
isdrag = true;
tx = parseInt(document.getElementById("moveid").style.left+0);
x = e.touches[0].pageX;
return false;
}
</script>

</head>
<body>
<div align="left" class="window">
<div id="moveid"  class="dragme">
这是一个可以通过触摸屏拖动的demo<br>
这个demo花费了我半天时间,原因是以前从来没有做过面向触摸屏的Web,按说mousedown,mouseup,mousemove和touchstart,touchend,touchmove
之间是可以互通的,也就是说一般面向pc开发的mouse时间对touch事件有效,据说是效率有差异。但是pc上测试没有任何问题,在手机上就是无效。
然后……
然后百度了很久很久……

</div>
</div>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  拖动 触摸 移动Web