龙空技术网

手写js实现拖拽div功能

小吊丝12138 672

前言:

今天你们对“jquery找div下的div”可能比较着重,小伙伴们都需要分析一些“jquery找div下的div”的相关知识。那么小编同时在网上搜集了一些有关“jquery找div下的div””的相关内容,希望同学们能喜欢,各位老铁们快快来了解一下吧!

先看效果图:

拖拽前

拖拽后

我在header处加了的id 然后通过其点击事件给其父容器根据鼠标移动来判断位置,写的比较简陋,只能按住黑框部分处才能进行拖拽

附上代码:

<!DOCTYPE html><html><head> <style type="text/css"> body { box-sizing: border-box; } .requirement_table { border: 1px solid #f1f1f1; width: 100%; } .trrow { border: 1px solid green; height: 59.5px; width: 100%; } .selectadd { height: 119px; width: 50px; background: yellow; float: left; } .feildgroup { width: 100%; } </style> <script type="text/javascript" src=""></script></head><body> <div class="requirement_table"> <div class="feildgroup"> <div style="width:100%;border: 1px solid red;"> <div class="selectadd">和(and)</div> <div class="trrow">条件A </div> <div class="trrow">条件B </div> </div> </div> </div> <div style="height: 200px;width: 200px;border: 1px solid red"> <div id="needmove" style="height: 50px;width: 200px;border: 1px solid black;text-align: center;">header</div> </div></body><script type="text/javascript">$.registerDrag = function(handle) { var _$handle = handle, qidianX, qidianY, _parentContainer, _pageX, _pageY, _isMove = false; var _left, _top, needshowX, needshowY; if (typeof handle === "string") { _$handle = $("#" + handle); } _parentContainer = _$handle.parent(); var parent_height = _$handle.outerHeight(); //未指定父类高度 获取为0 所以只能获取handle高度 var parent_width = _parentContainer.outerWidth(); var count = 0; _parentContainer.css("position", "absolute"); _$handle.mousedown(function(event) { _isMove = true; _pageX = event.pageX; //_pageX为鼠标按下位置 _pageY = event.pageY; qidianX = _parentContainer.offset().left; //起点框的位置 qidianY = _parentContainer.offset().top; //	$("#test").text("qidianX"+qidianX+"----qidianY"+qidianY+"----_pageX" + _pageX + " ------_pageY:" + _pageY); var _that = this; _parentContainer.css("opacity", 0.5); $(document).mousemove(function(event) { if (!_isMove) { return; } var maxwidth = window.innerWidth; var maxheight = window.innerHeight; needshowX = event.pageX - _pageX + qidianX; needshowY = event.pageY - _pageY + qidianY; if (needshowX < 0) needshowX = 0; if (needshowY < 0) needshowY = 0; if (needshowX + parent_width > maxwidth) needshowX = maxwidth - parent_width; if (needshowY + parent_height > maxheight) needshowY = maxheight - parent_height; //	$("#test").text("maxwidth:"+maxwidth+"maxheight:"+maxheight+"parentWidth:"+parent_width+"-parent_height"+parent_height+" qidianX"+qidianX+"-qidianY"+qidianY+"-_pageX" + _pageX + " ------_pageY:" + _pageY + "-------mouseposX" + event.pageX + "-------mouseposY:" + event.pageY + "------needshowX" + needshowX + "-------needshowY" + needshowY); _parentContainer.offset({ "left": needshowX, "top": needshowY }); }); }); $(document).mouseup(function(event) { if (_isMove) { _isMove = false; _parentContainer.css("opacity", 1); } //_isMove = false;  });}$(function() { $.registerDrag("needmove");});</script></html>

标签: #jquery找div下的div