本文分享一个使用js实现的鼠标拖动div的效果,不同于网上其他的案例,这里实现的是鼠标按在菜单上移动,整个DIV跟着移动的效果。具体细节就不分析了,自己看下面的代码吧!
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title></title> <script src="http://www.maopiaopiao.com/js/jquery.min.js" type="text/javascript" charset="utf-8"></script> <style type="text/css"> * {margin: 0;padding: 0;} #pic {width: 80px;height: 80px;position: absolute;left: 0;right: 0;border:1px solid #999;width:260px;height:380px;} a {border: 1px solid red;} #menu{cursor:move;height:50px;background-color:#ccc;border-bottom:1px solid #999;} </style> </head> <body> <div id="pic"> <div id="menu"></div> </div> <script type="text/javascript"> var drag = function (obj, moveObj) { obj.bind("mousedown", start); function start(event) { if (event.button == 0) { gapX = event.clientX - obj.offset().left; gapY = event.clientY - obj.offset().top; $(document).bind("mousemove", move); $(document).bind("mouseup", stop); } return false; } function move(event) { moveObj.css({ "left": (event.clientX - gapX) + "px", "top": (event.clientY - gapY) + "px" }); return false; } function stop() { $(document).unbind("mousemove", move); $(document).unbind("mouseup", stop); } } drag($("#menu"), $("#pic")); </script> </body> </html>