拖拽效果
刚学了一个拖拽效果,其实里面涉及的东西思想,很多,仔细琢磨下来对自身提高有一定的帮助
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box{
width: 100px;
height: 100px;
background-color: red;
border-radius: 50%;
position: fixed;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
var oBox = document.getElementById('box');
oBox.onmousedown = function(e){
//鼠标按下,触发事件,获取鼠标到box边缘的距离
var mouseToBox = {
//声明一个对象,装着鼠标距离box边缘的距离
x:e.offsetX,
y:e.offsetY
}
//console.log(e);
document.onmousemove = function(e){
var oBoxLocation = {
left:e.clientX - mouseToBox.x,
top:e.clientY - mouseToBox.y
//鼠标移动的时候设置一个left和top,用一个对象装着
//分别是鼠标距离文档的left和top,用鼠标距离文档(屏幕)的距离减去鼠标距离box边缘的距离
//其实这个left和top是指box左上角的坐标
}
if(oBoxLocation.left <= 0){//控制box不能小于屏幕飞出去
oBoxLocation.left = 0;
}else if(oBoxLocation.left >= document.documentElement.clientWidth - oBox.offsetWidth ){
/*用else if 而不是else.因为只要限制box在边缘区域,而不是对他进行
单纯大小于0的比较,所以用elseif,下面控制top也是一样的
obox.offsetWidth就是元素的宽度,也就是100px
document.documentelement.clientWidth指的是文档的宽度(屏幕拉的大小)
console.log(document.documentElement.clientWidth,oBox.offsetWidth);*/
oBoxLocation.left = document.documentElement.clientWidth - oBox.offsetWidth
//让他最大不能超过文档(屏幕)减去box这个元素的宽度
}
if(oBoxLocation.top <= 0){
oBoxLocation.top = 0;
}else if(oBoxLocation.top >= document.documentElement.clientHeight - oBox.offsetHeight){
oBoxLocation.top = document.documentElement.clientHeight - oBox.offsetHeight;
}
//算出来之后就要把值赋给box的left和top
oBox.style.left = oBoxLocation.left + "px";
oBox.style.top = oBoxLocation.top + "px";
}
//控制完小方块移动,发现一个问题,
//移动完不能暂停,接下来要设置一个让他随时暂停随时启动暂停
document.onmouseup = function(){
document.onmousemove = null;
document.onmouseup = null;
}
}
/* oBox.onmouseup = function(){
document.onmousemove = null;
oBox.style.left = 0 + "px";
oBox.style.top = 0 + "px"
} */
</script>
</body>
</html>