您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

js实现拖拽和吸附代码分享

2025/8/14 19:58:15发布23次查看
本文主要和大家分享js实现拖拽和吸附代码,希望能帮助到大家。
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>document</title> <style> * { padding: 0; margin: 0; } #big { width: 500px; height: 500px; background-color: #ccc; position: relative } #box { width: 100px; height: 100px; background-color: #f00; position: absolute } </style> <script> window.onload = function () { var box = document.getelementbyid('box'); var big = document.getelementbyid('big'); // 鼠标在box中的位置 var disx = 0, disy = 0; box.onmousedown = function (e) { var thise = e || event; disx = thise.clientx - box.offsetleft; disy = thise.clienty - box.offsettop; document.onmousemove = function (ev) { var thisevent = ev || event; var l = thisevent.clientx - disx; var t = thisevent.clienty - disy; if (l < 20) { l = 0; } else if (l > big.offsetwidth - box.offsetwidth - 20) { l = big.offsetwidth - box.offsetwidth; } if (t < 20) { t = 0; } else if (t > big.offsetheight - box.offsetheight - 20) { t = big.offsetheight - box.offsetheight; } box.style.left = l + 'px'; box.style.top = t + 'px'; document.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; } } e.preventdefault(); } } </script> </head> <body> <p id="big"> <p id="box"></p> </p> </body> </html>
相关推荐:
js代码实现鼠标拖拽div实例
js控制文件拖拽及获取拖拽内容
限制范围拖拽,磁性吸附。
以上就是js实现拖拽和吸附代码分享的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product