jQuery实现的简单拖拽功能示例【测试可用】

<!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> jQuery拖拽</title> <style type="text/css"> #box{ position:fixed; left:100px; top:100px; background-color:red; width:300px; height:200px; } #out{ height:2000px; } </style> <script src="https://libs.baidu.com/jquery/2.0.3/jquery.min.js"></script> <script> $(document).ready(function(){ var drafting=false; var offX,offY,mouseX,mouseY,winX,winY,x,y; $("#box").mousedown(function(event){ event.stopPropagation(); drafting=true; }); $(document).mousemove(function(event){ event.stopPropagation(); var e=event||window.event; mouseX=e.pageX||e.clientX+$(document).scrollLeft(); mouseY=e.pageY||e.clientY+$(document).scrollTop(); winX=$("#box").offset().left-$(document).scrollLeft(); winY=$("#box").offset().top-$(document).scrollTop(); if(drafting==false){ offX=mouseX-winX; offY=mouseY-winY; } x=mouseX-offX; y=mouseY-offY; $("#box").css({'left':x,'top':y}); }); $(document).mouseup(function(event){ event.stopPropagation(); drafting=false; }); }); </script> </head> <body> <div></div> <div></div> </body> </html>

这里使用在线HTML/CSS/JavaScript代码运行工具,可得到如下测试效果:

jQuery实现的简单拖拽功能示例【测试可用】

更多关于jQuery相关内容感兴趣的读者可查看本站专题:《jQuery拖拽特效与技巧总结》、《jQuery常用插件及用法总结》、《jQuery扩展技巧总结》、《jQuery常见经典特效汇总》、《jQuery页面元素操作技巧汇总》及《jquery选择器用法总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/86bb2413394dddf97e6e8382370d0ab7.html