jquery实现拖动效果(代码分享)

网络编程 2021-07-04 19:20www.168986.cn编程入门
本文主要分享了jquery实现拖动效果的示例代码。具有很好的参考价值,狼蚁网站SEO优化跟着长沙网络推广一起来看下吧

话不多说,请看代码

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
</head>
<body>
 <style type="text/css">
 .page{text-align:left;}
 .dragDiv{border:1px solid #ddd; padding:10px; width:300px; margin:0 auto; border-radius:4px; box-shadow:0 1px 2px #fefefe; position: fixed;}
 </style>
 <div class="dragDiv" id="drag">
 <div class="drag-head">自己动手试试</div>
 <div class="drag-body">
 点击鼠标拖拖看
 </div>
 </div>
</body>
<script src="http://apps.bdimg./libs/jquery/2.1.4/jquery.min.js"></script>
<script>
 var _drag = {};
 _drag. = 0; //拖动过的位置距离上边
 _drag.left = 0; //拖动过的位置距离左边
 _drag.maxLeft; //距离左边最大的距离
 _drag.maxTop; //距离上边最大的距离
 _drag.dragging = false; //是否拖动标志
 //拖动函数
 function bindDrag(el){ 
 var winWidth = $(window).width(), winHeight =$(window).height(),objWidth = $(el).outerWidth(), objHeight = $(el).outerHeight();
 _drag.maxLeft = winWidth - objWidth, _drag.maxTop = winHeight - objHeight;
 var els = el.style,x=0,y=0;
 var objTop = $(el).offset()., objLeft = $(el).offset().left;
 $(el).mousedown(function(e){ 
 _drag.dragging = true;
 _drag.isDragged = true;
 x = e.clientX - el.offsetLeft; 
 y = e.clientY - el.offsetTop; 
 el.setCapture && el.setCapture(); 
 $(document).bind('mousemove',mouseMove).bind('mouseup',mouseUp);
 return false;
 }); 
 function mouseMove(e){ 
 e = e || window.event;
 if(_drag.dragging){
 _drag. = e.clientY - y; 
 _drag.left = e.clientX - x;
 _drag. = _drag. > _drag.maxTop ? _drag.maxTop : _drag.;
 _drag.left = _drag.left > _drag.maxLeft ? _drag.maxLeft : _drag.left;
 _drag. = _drag. < 0 ? 0 : _drag.;
 _drag.left = _drag.left <0 ? 0 : _drag.left;
 els. = _drag. + 'px'; 
 els.left = _drag.left+ 'px';
 return false;
 }
 } 
 function mouseUp(e){ 
 _drag.dragging = false; 
 el.releaseCapture && el.releaseCapture(); 
 e.cancelBubble = true;
 $(document).unbind('mousemove',mouseMove).unbind('mouseup',mouseUp); 
 }
 $(window).resize(function(){
 var winWidth = $(window).width(),
 winHeight = $(window).height(),
 el = $(el),
 elWidth = el.outerWidth(),
 elHeight = el.outerHeight(),
 elLeft = parseFloat(el.css('left')),
 elTop = parseFloat(el.css(''));
 _drag.maxLeft = winWidth - elWidth;
 _drag.maxTop = winHeight - elHeight;
 _drag. = _drag.maxTop < elTop ? _drag.maxTop : elTop;
 _drag.left = _drag.maxLeft < elLeft ? _drag.maxLeft : elLeft;
 el.css({
 :_drag.,
 left:_drag.left
 })
 })
 } 
 bindDrag(document.getElementById('drag'));
</script>
</html>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望多多支持狼蚁SEO!

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by