当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jQuery实现的简单拖拽功能示例【测试可用】

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

2018年08月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了jquery实现的简单拖拽功能。分享给大家供大家参考,具体如下:

<!doctype html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>www.jb51.net 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="http://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 id="box"></div>
    <div id="out"></div>
  </body>
</html>

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

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

希望本文所述对大家jquery程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网