jQuery拖拽原理实例

今天药忘吃喽~ 2021-11-19 11:40 432阅读 0赞

HTML源代码

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>拖拽实例</title>
  6. <link rel="stylesheet" href="drag.css">
  7. <script src="http://libs.baidu.com/jquery/1.7.2/jquery.min.js"></script>
  8. <script src="drag.js"></script>
  9. </head>
  10. <body>
  11. <div></div>
  12. </body>
  13. </html>

CSS源代码

  1. *{
  2. margin: 0;
  3. padding:0;
  4. }
  5. div{
  6. width: 100px;
  7. height: 100px;
  8. background: #f00;
  9. cursor: pointer;
  10. position: absolute;
  11. left: 0;
  12. top: 0;
  13. }

JS源代码

  1. $(function(){
  2. $('div').mousedown(function(e){
  3. //offset()在匹配的元素集合中,获取的第一个元素的当前坐标,坐标相对于文档
  4. var positionDiv = $(this).offset();
  5. var distenceX = e.pageX - positionDiv.left;
  6. var distenceY = e.pageY - positionDiv.top;
  7. // alert(positionDiv.left);
  8. $(document).mousemove(function(e) {
  9. var x = e.pageX - distenceX;
  10. var y = e.pageY - distenceY;
  11. //防止将元素拖拽出浏览器窗口
  12. if(x<0){
  13. x=0;
  14. }else if(x>$(document).width()-$('div').outerWidth(true)){
  15. x=$(document).width()-$('div').outerWidth(true);
  16. }
  17. if(y<0){
  18. y=0
  19. }else if(y>$(document).height()-$('div').outerHeight(true)){
  20. y=$(document).height()-$('div').outerHeight(true);
  21. }
  22. $('div').css({
  23. 'left':x+'px',
  24. 'top':y+'px'
  25. });
  26. });
  27. $(document).mouseup(function() {
  28. //unbind和off都可以解除绑定时间
  29. $(document).unbind('mousemove');
  30. });
  31. });
  32. });

转载于:https://www.cnblogs.com/littlefly/p/3677509.html

发表评论

表情:
评论列表 (有 0 条评论,432人围观)

还没有评论,来说两句吧...

相关阅读

    相关 jQuery实现面板

    一.实现功能 1.首先页面有一个面板或者对话框,有长和宽,可以设置为一个div。 2.当把鼠标over到div的某个位置时,鼠标的箭头图片变为一个拖拽的图片。 3.接