代码描述:JavaScript 移动端 拖动效果。JavaScript移动端触屏拖动效果
分享一段代码实例,他实现了移动端触屏拖动效果。 代码实例如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.51qianduan.com/" /> <title>51前端</title> <style> .box { width: 100px; height: 100px; background: red; } </style> <script> function Touch(ele) { var _this = this; this.ele = ele; this.transP = { x: 0, y: 0 }; this.events = { handleEvent: function(event) { switch (event.type) { case 'touchstart': _this.start(event); break; case 'touchmove': _this.move(event); break; case 'touchend': _this.end(event); break; } } } } Touch.prototype = { start: function(ev) { var touches = ev.targetTouches[0], _this = this; this.disP = { x: touches.pageX - this.transP.x, y: touches.pageY - this.transP.y, id: touches.identifier }; console.log('aaa'); document.addEventListener('touchmove', _this.events, false); document.addEventListener('touchend', _this.events, false); }, move: function(ev) { var touches = ev.targetTouches[0]; if (touches.identifier == this.disP.id) { console.log('move'); this.transP = { x: touches.pageX - this.disP.x, y: touches.pageY - this.disP.y }; this.ele.style.transform = 'translate3d(' + this.transP.x + 'px,' + this.transP.y + 'px,0)'; this.ele.style.Webkittransform = 'translate3d(' + this.transP.x + 'px,' + this.transP.y + 'px,0)'; } }, end: function(ev) { ev = ev || window.event; var _this = this; if (ev.changedTouches[0].identify == this.disP.id) { document.removeEventListener('touchmove', _this.events, false); document.removeEventListener('touchend', _this.events, false); } }, init: function() { var _this = this; this.ele.addEventListener('touchstart', _this.events, false); } }; window.onload = function() { var box = document.querySelector('#box'), touch = new Touch(box); touch.init(); }; </script> </head> <body> <div id="box" class="box"></div> </body> </html>
请绑定手机号,在继续操作
注意:只有绑定手机以后,才可使用网站全部功能