拖拽功能实现
<!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>
#box1{
width: 100px;
height: 100px;
background-color: red;
position: fixed;
}
#box2{
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
left: 200px;
top: 200px;
}
</style>
<script>
window.onload = function(){
/**
* 拖拽
* 1 当鼠标在被拖拽元素移动时 开始拖拽 onmousedown
* 2 当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove
* 3 当鼠标松开时,被 拖拽元素固定在当前位置 onmouseup
*
*/
var box1 = document.getElementById("box1");
var box2 = document.getElementById("box2");
// 开启box1
drag(box1);
// 开启box2
drag(box2);
}
/**
* 提取 一个专门用来设置拖拽的函数
* 参数: 开启拖拽的元素
*
*/
function drag(obj){
// 1 当鼠标在被拖拽元素移动时 开始拖拽 onmousedown
obj.onmousedown = function(event){
// 设置 obj 捕获所有鼠标按下的事件
// setCapture() 只有ie 支持 在 chrome调用 会报错
// if(obj.setCapture){
// obj.setCapture();
// }
obj.setCapture && obj.setCapture();
event = event ||window.event;
// div 的偏移量 鼠标.clientX - 元素.offsetLeft
// div 的偏移量 鼠标.clientY - 元素.offsetTop
var ol = event.clientX - obj.offsetLeft;
var ot = event.clientY - obj.offsetTop;
// 为document 绑定一个onmousemove 事件
document.onmousemove = function(event){
// 2 当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove
event = event ||window.event;
// 获取鼠标坐标
var left = event.clientX - ol;
var top = event.clientY - ot;
var objW = obj.offsetWidth;
var objH = obj.offsetHeight;
var docW = document.documentElement.clientWidth;
var docH = document.documentElement.clientHeight;
// 限制临界点 左边
if( left < 0){
left = 0;
}
if(left > docW - objW){
left = docW - objw
}
// 限制临界点 顶部
if( top < 0){
top = 0;
}
if( top > docH - objH){
top = docH - objH;
}
// 修改box的位置
obj.style.left = left + 'px';
obj.style.top = top + 'px';
};
// 为元素绑定一个鼠标松开事件
document.onmouseup = function(){
// 3 当鼠标松开时,被 拖拽元素固定在当前位置 onmouseup
// 取消document的onmousemove 事件
document.onmousemove = null;
// 取消document的onmouseup 事件
document.onmouseup = null;
// 当鼠标松开时 取消对事件的捕获
// if(obj.releaseCapture){
// obj.releaseCapture();
// }
obj.releaseCapture && obj.releaseCapture();
};
/**
* 当 拖拽一个网页中的内容时, 浏览器会默认 去 搜索引擎中搜索
* 此时会导致拖拽功能的异常
* 如果不希望发生这个行为, 则可以 return false 来取消默认行为
* 对 ie8 不起作用
*/
return false;
}
}
</script>
</head>
<body>
我是一段文字
<div id="box1"> </div>
<div id="box2"> </div>
</body>
</html>
我是Eric,手机号是13522679763

浙公网安备 33010602011771号