- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>draggable</title>
- <style type="text/css">
- .ui-draggable{
- position: absolute;
- cursor: move;
- }
- .ui-draggable-opacity{
- filter:alpha(opacity =50);
- -moz-opacity:0.5 ;
- -khtml-opacity: 0.5;
- opacity: 0.5;
- }
- </style>
- </head>
- <body>
- <div id='demo' style='width:200px;height:100px;background: #ccc;'>
- drag me!
- </div>
- <script type="text/javascript" src='http://code.jquery.com/jquery-latest.min.js'></script>
- <script type="text/javascript">
- /**
- * jquery 实现拖动
- * @author huxiaoqi
- */
- (function($){
- $.fn.draggable = function(){
- var self = $(this);
- self.addClass('ui-draggable');
- var width = self.width();
- var height = self.height();
- var position = self.position();
- var pos = {
- mouseX:0,
- mouseY:0,
- offsetX:0,
- offsetY:0
- };
- self.bind({'mousedown':function(e){
- self.addClass('ui-draggable-opacity');
- position = self.position();
- pos.offsetX = e.pageX - position.left;
- pos.offsetY = e.pageY - position.top;
- //记录鼠标位置和目标位置的相对位置
- $(document).bind('mousemove',function(e){
- position = self.position();
- pos.mouseX = e.pageX;
- pos.mouseY = e.pageY;
- self.moveTo(pos.mouseX - pos.offsetX , pos.mouseY - pos.offsetY);
- });
- },
- 'mouseup':function(e){
- $(document).unbind('mousemove');
- self.removeClass('ui-draggable-opacity');
- }
- });
- self.moveTo = function(x,y){
- self.css({'left':x,'top':y});
- return self;
- };
- };
- })(jQuery);
- $('#demo').draggable();
- </script>
- </body>
- </html>
转载于:https://blog.51cto.com/huxiaoqi/851006