本文将详细介绍拖拽的实现过程,会使用到js的三个事件(鼠标按下mousedown、鼠标移动mousemove、鼠标抬起mouseup),利用这三个事件即可完成拖拽效果。
在没有拖拽到最右端的情况下,会自动返回,效果图如下:
具体实现代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
300px;
height: 30px;
margin: 40px auto;
border: 1px #eee solid;
position: relative;
}
p{
padding: 0;
margin: 0;
float: left;
height: 30px;
background: yellow;
}
span{
float: left;
30px;
height: 30px;
text-align: center;
line-height: 30px;
background-color: violet;
position: absolute;
cursor: pointer;;
}
</style>
</head>
<body>
<div>
<p></p><span>>></span>
</div>
</body>
<script src="../move.js"></script>
<script>
class tz{
constructor(){
this.div = document.querySelector('div');
this.p = document.querySelector('p');
this.span = document.querySelector('span');
this.init();
}
init(){
// 鼠标按下记录坐标
this.span.onmousedown = (eve)=>{
var e = eve || window.event;
this.left = e.offsetX;
// 鼠标按下之后执行后面的鼠标移动和鼠标抬起
this.move();
this.up();
}
}
// 鼠标移动事件
move(){
var that = this;
document.onmousemove = function(eve){
var e = eve || window.event;
that.l = e.pageX- that.div.offsetLeft - that.left;
if(that.l<0){that.l=0};
if(that.l > that.div.offsetWidth - that.span.offsetWidth){
that.l = that.div.offsetWidth - that.span.offsetWidth;
that.span.innerHTML = '√';
}
that.span.style.left = that.l + 'px';
that.p.style.width = that.l + 'px';
return false;
}
}
// 鼠标抬起事件
up(){
document.onmouseup = ()=>{
document.onmousemove=null;
document.onmouseup = null;
if(this.l< this.div.offsetWidth - this.span.offsetWidth){
move(this.span,{left:0});
move(this.p,{0});
}
}
}
}
new tz();
</script>
</html>
如果有什么疑问,请在评论区留言