元素拖拽边缘管理,轨迹及回放
知识点:
-
边缘管理:右边和下边需要减去盒子自身的宽高
-
每次获取得坐标值需要存储到数组中
-
点击回放按钮时,需要给数组第一个添加一个0,0的坐标对象,不然不能回到原位
-
当数组为空时,清除定时器,结束回放
-
合理使用各种坐标值和自身宽高的属性
-
数组的删除返回的是删除的那个元素
-
当放开鼠标时,需要清除按下和移动事件,优化代码
<script type="text/javascript">
window.onload = function () {
var box = document.querySelector("div");
var reset = document.querySelector("input");
var list = [];
box.onmousedown = function (ev) {
ev = ev || window.event;
var boxX = ev.offsetX;
var boxY = ev.offsetY;
document.onmousemove = function (ev) {
ev = ev || event;
var x = ev.pageX - boxX;
var y = ev.pageY - boxY;
if (x < 0) {
x = 0
} else if (x > innerWidth - box.offsetWidth) {
x = innerWidth - box.offsetWidth;
}
if (y < 0) {
y = 0
} else if (y > innerHeight - box.offsetHeight) {
y = innerHeight - box.offsetHeight;
}
box.style.left = x + "px";
box.style.top = y + "px";
var box2 = document.createElement("span")
box2.style.left = x + "px";
box2.style.top = y + "px";
document.body.appendChild(box2);
list.push({
x: x,
y: y
});
}
document.onmouseup = function () {
document.onmousemove = null;
box.onmousedouw = null;
}
}
reset.onclick = function (ev) {
ev = ev || window.event;
ev.defaultPrevented ? ev.defaultPrevented() : ev.returnValue = false;
list.unshift({
x: 0,
y: 0
})
var timer = setInterval(function(){
if(list == null ){
clearInterval(timer);
}
var last = list.pop();
box.style.left = last.x + "px";
box.style.top = last.y + "px";
},50)
}
}
</script>
</head>
<body>
<div>
元素拖拽
</div>
<input type="reset" value="重置">
</body>
元素拖拽,精度条
知识点:
-
event.clientX event.clientX 获取鼠标距浏览器可视区域的位置
-
box.offsetLeft box.offsetTop 获取盒子本身的距离父级定位的位置
-
box.offsetWidth box.offsetHeight 获取盒子自身的宽高
-
最后清除点击和移动事件,优化代码
-
获取对之间的关系和差值
<body>
<div id="progress">
<div>
<p></p>
<p></p>
</div>
<span>0%</span>
</div>
<script>
var sp = document.querySelector("span");
var aP1 = document.querySelectorAll("p")[0];
var aP2 = document.querySelectorAll("p")[1];
var box = document.querySelector("#progress>div");
aP2.onmousedown = function(ev){
ev = ev || window.event;
var x = ev.clientX - aP2.offsetLeft;
document.onmousemove = function(ev){
ev = ev || window.event;
var moveX = ev.clientX - x;
if(moveX < 0){
moveX = 0;
}else if(moveX > box.offsetWidth - aP2.offsetWidth){
moveX = box.offsetWidth - aP2.offsetWidth;
}
aP2.style.left = moveX + "px";
aP1.style.width = moveX + "px";
var percentage = parseInt(moveX/ (box.offsetWidth - aP2.offsetWidth)*100);
sp.innerHTML = percentage+"%";
return false
}
document.onmouseup = function(){
document.onmousemove = null;
document.onmouseup = null;
}
}
</script>
</body>
实现效果
![在这里插入图片描述](https://img-blog.csdnimg.cn/5faeb806f6c84eeaaa389f8bedc4b2bc.png#pic_center)