最近开发小程序,用到小程序里的拖拽效果,研究了下底层的原理,发现只要以下三点就可以完成拖拽效果。
实现拖拽效果的三个步骤:
1.鼠标按下,元素开始响应鼠标动作----onmousedown
2.鼠标移动,元素开始跟随鼠标位移而位移----onmousemove
3.鼠标松开,元素停止响应鼠标动作-----onmouseup
先开始准备工作:
// 注意,开启定位必不可少
<style>
#box1 {
height: 200px;
width: 200px;
background-color: red;
position: absolute;
}
</style>
<div id="box1"></div>
1.先获取一下box1,然后给它绑定一个鼠标按下的事件;
2.当鼠标按下时,就要开始响应鼠标的位移了,所以用到了onmousemove;
3.位移时让鼠标的XY轴的值等于box1的值event.clientX,event.clientY
4.如果鼠标松开,当然时停止响应鼠标的位移动作,
document.onmousemove = null;
5.至于document.onmouseup = null;的话 自己alert一下会发现,如果不这么做,鼠标在按下任意空白处时,它并没有被销毁,所以就给他也null一下;
<script>
var box1 = document.getElementById("box1");
box1.onmousedown = function () {
document.onmousemove = function (event) {
event = event || window.event
var left = event.clientX;
var top = event.clientY;
box1.style.left = left + "px";
box1.style.top = top + "px";
}
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
}
</script>
到这里还由一些缺陷:
1.实际应用的时候,页面上往往不会只有 box1这一个元素,假设现在页面由box2,当鼠标拖拽到box2且完全重合时,box1就不能继续拖动了,因为现在鼠标已经不在box1了,所以,在css里加 z-index: 999999;让box1始终在最顶层即可;
2.以上代码执行过程中,当鼠标在box1按下时,光标位置始终在左上角,解决方法暂时就是
box1.style.left = left -100 + "px";
box1.style.top = top -100 + "px";
这样会稍微好看一点。
以下是完整代码:
<style>
#box1 {
height: 200px;
width: 200px;
background-color: red;
position: absolute;
z-index: 999999;
}
#box2 {
height: 200px;
width: 200px;
background-color: yellow;
position: absolute;
top: 300px;
left: 300px;
}
</style>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
<script>
var box1 = document.getElementById("box1");
box1.onmousedown = function () {
document.onmousemove = function (event) {
event = event || window.event
var left = event.clientX;
var top = event.clientY;
box1.style.left = left - 100 + "px";
box1.style.top = top - 100 + "px";
}
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
}
</script>
event = event || window.event 处理了下兼容问题
网友评论