- <!DOCTYPE html>
- <html lang="zh_CN">
- <head>
- <title>拖拽</title>
- <meta charset="utf-8" />
- <style>
- .move_box{width:500px;height:170px;padding-top:30px;position:fixed;top:0;right:0;background:#F00;overflow:auto;}
- .move_box_title{width:100%;height:30px;margin-top:-30px;background:#0F0;}
- </style>
- <script src1="js/jquery-1.8.3.min.js"></script>
- <script>
- $.fn.extend({
- drag:function (config){
- if(config){
- if(config.x){
- config.x = config.x > 0 ? (config.x > $(this).width()?$(this).width():config.x):$(this).width();
- }else{
- config.x = $(this).width();
- }
- if(config.y){
- config.y = config.y > 0 ? (config.y > $(this).height()?30:config.y):30;
- }else{
- config.y = $(this).height();
- }
- }else{
- config = config||{x:$(this).width(),y:30};
- }
- $(this).bind('mousedown',function (e){
- //计算鼠标点击位置,与div页面偏移量
- var offset_x = e.clientX - $(this).left();
- var offset_y = e.clientY - $(this).top();
- //判断偏移量是否在偏移范围内
- if( (offset_y <= config.y && offset_y >= 0) && (offset_x <= config.x && offset_x >= 0)){
- $(this).CSS({"cursor":"move"});
- $(this).bind("mousemove",function (e){
- $(this).left(e.clientX - offset_x);
- $(this).top(e.clientY - offset_y);
- });
- }
- $(this).bind('mouseup',function (){$(this).unbind("mousemove");$(this).css({"cursor":""});});
- $(this).bind('mouseout',function (){$(this).unbind("mousemove");$(this).css({"cursor":""});});
- });
- },
- left: function (pos){
- if(pos){
- $(this).css({"left" : pos+"px"});
- }else{
- return $(this).position().left;
- }
- },
- top:function (pos){
- if(pos){
- $(this).css({"top" : pos+"px"});
- }else{
- return $(this).position().top;
- }
- }
- });
- $(function (){
- $('#move_box').drag({x:150,y:45});
- });
- </script>
- </head>
- <body>
- <div id="move_box" class="move_box">
- <div class="move_box_title"></div>
- </div>
- </body>
- </html>
- //该片段来自于http://www.codesnippet.cn/detail/130520149543.html
来源: http://www.codesnippet.cn/detail/130520149543.html