A-A+
Javascript中node.js触摸事件处理
随着移动开发需求的逐渐增大,以mobile safari为例,增加了对触摸事件的支持,下面举个例子来说明,页面结构.
页面结构,代码如下:
- <section id = "content">
- <section id = "detail">node.js是基于google的开源javascriptV8引擎开发的Web I/O服务器,原本node.js只能运行在POSIX系统环境下(Linux或者Mac OS),在Windows环境下需要安装虚拟环境,在这里通过安装Cygwin在Windows环境下构建linux虚拟环境。</section>
- </section>
样式,代码如下:
- * {margin:0;padding:0;}
- body{font-family: Calibri, Arial, Helvetica, sans-serif;}
- #content {
- width:100px;
- height:100px;
- background:#ffc000;
- padding:5px;
- overflow:hidden;
- }
- #detail {
- width:100px;
- float:left;
- }
脚本实现,触控的支持是对于touchstart,touchmove的事件的监听,代码如下:
- var $ = function(obj){
- return 'string' == typeof obj ? document.getElementById(obj) : obj;
- }
- var touchInfo = {};
- var content = $("content");
- var detail = $("detail");
- content.ontouchstart = function(e){
- e.preventDefault();
- if(detail.offsetHeight > content.offsetHeight){
- var touch = e.touches[0];
- touchInfo.obj = touch;
- touchInfo.y = touch.screenY;
- touchInfo.top = parseInt(document.defaultView.getComputedStyle(detail,null).marginTop);
- }
- }
- content.ontouchend = function(e){
- touchInfo = {}
- }
- content.ontouchmove = function(e){
- if(detail.offsetHeight > content.offsetHeight){
- var touch = e.touches[0];
- var top = touchInfo.top + (touch.screenY - touchInfo.y);
- var offset = this.offsetHeight - detail.offsetHeight - 10;
- top = top > 0 ? 0 : (top < offset ? offset : top);
- detail.style.marginTop = top+ "px";
- }
- }
e.touches[0]为触摸的对象,touch.screeX和touch.screenY为触摸的坐标 需要添加e.preventDefault()来取消冒泡,防止对当前对象的触摸触发对document的触摸事件