金狮镖局 Design By www.egabc.com
本文实例为大家分享了JS+DIV实现拖动效果的具体代码,供大家参考,具体内容如下
效果图
思路
代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="main" style="background-color: aqua;width: 100px;height: 100px;position: absolute;left: 50px;top: 50px"> <div id="title" style="height: 10px;width:100%;background-color: antiquewhite;position: absolute;left: 0px;top: 0px"></div> <div class="box"></div> </div> <script> var startx; var starty; var startLeft; var startTop; var titleDiv=document.getElementById("title"); var mainDiv=document.getElementById("main"); var isDown=false; // 鼠标按下 function movedown(e){ e=e"px"; mainDiv.style.top = e.clientY - (starty - startTop)+"px"; } } // 鼠标松开 function moveup(){ isDown=false; } titleDiv.οnmοusedοwn=movedown; titleDiv.οnmοusemοve=move; titleDiv.οnmοuseup=moveup; </script> </body> </html>
优化(封装,以及解决拖动问题(事件捕获))
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="main" style="background-color: aqua;width: 100px;height: 100px;position: absolute;left: 50px;top: 50px"> <div id="title" style="height: 10px;width:100%;background-color: antiquewhite;position: absolute;left: 0px;top: 0px"></div> <div class="box"></div> </div> <script> function Mover(title) { this.obj = title; this.startx = 0; this.starty; this.startLeft; this.startTop; this.mainDiv = title.parentNode; var that = this; this.isDown = false; this.movedown = function (e) { e = e "px"; that.mainDiv.style.top = e.clientY - (that.starty - that.startTop) + "px"; } } this.moveup = function () { that.isDown = false; if (!window.captureEvents) { this.releaseCapture(); } //事件捕获仅支持ie } this.obj.onmousedown = this.movedown; this.obj.onmousemove = this.move; this.obj.onmouseup = this.moveup; //非ie浏览器 document.addEventListener("mousemove", this.move, true); } var mover = new Mover(document.getElementById("title")); //写两个是为了解决 ie 和非ie 浏览器关于事件捕获 的兼容性问题 </script> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
标签:
JS,DIV,拖动
金狮镖局 Design By www.egabc.com
金狮镖局
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
金狮镖局 Design By www.egabc.com
暂无JS+DIV实现拖动效果的评论...
更新日志
2024年10月09日
2024年10月09日
- 【原神】V5.0攻略 | 林尼攻略一图流
- 李翊君.1993-相思的烈酒【上华】【WAV+CUE】
- 古巨基.1998-LEO.KU(国)【千禧年代】【WAV+CUE】
- 郭子.2001-原来你什么都不想要创作集丫滚石】【WAV+CUE】
- 《使命召唤:黑色行动6》新预告公布!10月25日发售
- Atlus《暗喻幻想》媒体评分汇总:高分好评如潮!
- 2024金摇杆奖提名揭晓 《黑神话》角逐最佳视觉设计!
- 群星《新说唱2024 第3期 (上)》[320K/MP3][32.76MB]
- 群星《新说唱2024 第3期 (上)》[FLAC/分轨][95.38MB]
- 群星《新说唱2024 第3期 (下)》[320K/MP3][31.36MB]
- 幻兽帕鲁手游什么时候正式上线 最新消息一览
- 西普大陆BOSS位置盘点 解锁天启纪元玩法
- 西普大陆精灵进阶培养攻略 精灵养成指南
- dnf手游法控法系职业哪个强 dnf手游法控法系职业强度排行
- 魔兽世界血藤护目镜图纸在哪买 wlk血藤护目镜图纸购买位置介绍