本文通过拖拽案例,实现“跟随鼠标、边界限定、轨迹回放”三大效果;
完整代码中有详尽注释,故不再进行细致讲解;
对于案例中需要注意的重点或易错点问题,会总结在最后。
效果图(仅演示左、上边界限定)
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>盒子拖拽</title>
<style>
body{
margin: 0;
padding: 0;
}
#box{
width: 100px;
height: 100px;
background: skyblue;
position: absolute;
/* 盒子在页面中的初始位置,可以随意设置 */
left: 200px;
top: 200px;
}
#btn{
display: inline-block;
width: 80px;
height: 30px;
font-size: 16px;
cursor: pointer;
outline: none;
}
<