js实现适配移动端的拖动效果
程序员文章站
2022-06-22 14:26:20
本文实例为大家分享了js实现适配移动端的拖动效果,供大家参考,具体内容如下
1.html
本文实例为大家分享了js实现适配移动端的拖动效果,供大家参考,具体内容如下
1.html
<div id="div1"> <div id="div2"></div> </div>
2.js
var flag = false; var cur = { x: 0, y: 0 } var nx, ny, dx, dy, x, y; function down() { flag = true; var touch; if(event.touches) { touch = event.touches[0]; } else { touch = event; } cur.x = touch.clientx; cur.y = touch.clienty; dx = div2.offsetleft; dy = div2.offsettop; } function move() { if(flag) { var touch; if(event.touches) { touch = event.touches[0]; } else { touch = event; } nx = touch.clientx - cur.x; ny = touch.clienty - cur.y; x = dx + nx; y = dy + ny; div2.style.left = x + "px"; div2.style.top = y + "px"; //阻止页面的滑动默认事件 document.addeventlistener("touchmove", function() { event.preventdefault(); }, false); } } //鼠标释放时候的函数 function end() { flag = false; } var div2 = document.getelementbyid("div2"); div2.addeventlistener("mousedown", function() { down(); }, false); div2.addeventlistener("touchstart", function() { down(); }, false) div2.addeventlistener("mousemove", function() { move(); }, false); div2.addeventlistener("touchmove", function() { move(); }, false) document.body.addeventlistener("mouseup", function() { end(); }, false); div2.addeventlistener("touchend", function() { end(); }, false);
效果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 正则表达式的应用