A-A+

Javascript中node.js触摸事件处理

2016年01月28日 前端设计 暂无评论 阅读 6 views 次

随着移动开发需求的逐渐增大,以mobile safari为例,增加了对触摸事件的支持,下面举个例子来说明,页面结构.

页面结构,代码如下:

  1. <section id = "content">  
  2. <section id = "detail">node.js是基于google的开源javascriptV8引擎开发的Web I/O服务器,原本node.js只能运行在POSIX系统环境下(Linux或者Mac OS),在Windows环境下需要安装虚拟环境,在这里通过安装Cygwin在Windows环境下构建linux虚拟环境。</section>  
  3. </section>   

样式,代码如下:

  1.  * {margin:0;padding:0;}  
  2. body{font-family: Calibri, ArialHelveticasans-serif;}  
  3. #content {  
  4.     width:100px;  
  5.     height:100px;  
  6.     background:#ffc000;  
  7.     padding:5px;  
  8.     overflow:hidden;  
  9. }  
  10. #detail {  
  11.     width:100px;  
  12.     float:left;  
  13. }   

脚本实现,触控的支持是对于touchstart,touchmove的事件的监听,代码如下:

  1. var $ = function(obj){  
  2.     return 'string' == typeof obj ? document.getElementById(obj) : obj;  
  3. }  
  4. var touchInfo = {};  
  5. var content = $("content");  
  6. var detail = $("detail");  
  7. content.ontouchstart = function(e){  
  8.     e.preventDefault();  
  9.     if(detail.offsetHeight &gt; content.offsetHeight){  
  10.         var touch = e.touches[0];  
  11.         touchInfo.obj = touch;  
  12.         touchInfo.y = touch.screenY;  
  13.         touchInfo.top = parseInt(document.defaultView.getComputedStyle(detail,null).marginTop);  
  14.     }  
  15. }  
  16. content.ontouchend = function(e){  
  17.     touchInfo = {}  
  18. }  
  19. content.ontouchmove = function(e){  
  20.     if(detail.offsetHeight &gt; content.offsetHeight){  
  21.         var touch = e.touches[0];  
  22.         var top = touchInfo.top + (touch.screenY - touchInfo.y);  
  23.         var offset = this.offsetHeight - detail.offsetHeight - 10;  
  24.         top = top &gt; 0 ? 0 : (top &lt; offset ? offset : top);  
  25.         detail.style.marginTop = top+ "px";  
  26.     }  
  27. }  

e.touches[0]为触摸的对象,touch.screeX和touch.screenY为触摸的坐标 需要添加e.preventDefault()来取消冒泡,防止对当前对象的触摸触发对document的触摸事件

标签:

给我留言