Learn a jquery plug-in every day-do drag effect 1
Do drag effect 1
The target effect is the effect of dragging the menu order from the side menu seen from the B station, but it is uncomfortable not to finish.
Target effect and current effect
Code part
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>做拖动效果</title>
<script src="js/jquery-3.4.1.min.js"></script>
<style>
*{
margin: 0px;
padding: 0px;
user-select: none;
}
#ui{
border: 1px solid lightgray;
display:inline-block;
margin: 20px;
position: relative;
}
.li{
width: 80px;
height: 20px;
display: flex;
justify-content: center;
align-items: center;
font-size: 12px;
}
.che{
background-color: rgb(0,161,214);
color: white;
position:absolute;
}
</style>
</head>
<body>
<div id="ui">
<div class="li">菜单1</div>
<div class="li">菜单2</div>
<div class="li">菜单3</div>
<div class="li">菜单4</div>
<div class="li">菜单5</div>
<div class="li">菜单6</div>
<div class="li">菜单7</div>
<div class="li">菜单8</div>
<div class="li">菜单9</div>
<div class="li">菜单10</div>
<div class="li">菜单11</div>
<div class="li">菜单12</div>
<div class="li">菜单13</div>
<div class="li">菜单14</div>
<div class="li">菜单15</div>
</div>
</body>
</html>
<script>
$(function(){
var $tc =$("<div class='li'></div>")//填充部分
var fl = 0;
//假如鼠标按下了,就浮动这个dom并且制造一个临时的dom填充位置
$(".li").mousedown(function(e){
var that = $(this);
that.attr("data-flag","1");
that.after($tc)
$(".li").removeClass("che");
that.addClass("che");
var y =that[0].offsetTop;
that.css("top",y);
fl = e.offsetY;
})
//按下拖动的过程中,处于absolute状态的dom不断校正自己与鼠标相同的位置,同时监控它与填充dom的位置差距,只要超过一个li的高度那么就向上或者向下挪动这个dom的位置,以此达到预设的效果拖动的效果,当然还得有边界效果,拖至顶端或者底部都应该要正确的反馈效果
$(".li").mousemove(function(e){
var that =$(this);
var par =$("#ui")
var flag = $(this).attr("data-flag");
if(flag==1){
var y =e.offsetY
console.log(y)
}
})
//假如鼠标放松了,就把当前拖拽的这个替换掉填充的dom
$(".li").mouseup(function(e){
var that = $(this);
that.attr("data-flag","0");
$(".li").removeClass("che");
$tc.remove();
})
})
</script>
Idea explanation
- The comments in js have been marked up
- The problem is that I can't get the relative position of the event to this container at this time through mousemove. The position obtained according to this method is all obscured by the upper sub-container, and there is no way, it is uncomfortable, and I still can't find a way.
- Never end, think about how to do it tomorrow.