<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖拽</title>
<style>
*{margin: 0;padding: 0;}
#box{
position:absolute;width: 100px;
height:100px;
background: red;}
</style>
<script src="js-拖拽.js">
var obox=
document.
getElementById(
'box')
;
obox.
onmousedown=
function (ev) {
var e=ev ||
window.
event;
var li=e.
clientX-obox.
offsetLeft; //鼠标点击的位置到div左边框的距离
var lT=e.
clientY-obox.
offsetTop; //鼠标点击的位置到div上边框的距离
// 针对低版本IE的方法,setCapture方法在oBox元素和下面的元素中间添加了一个透明层
if(obox.
setCapture)
{
obox.
setCapture()
;
}
document.
onmousemove=
function (ev) {
var e = ev ||
window.
event;
var il = e.
clientX - li
; //计算移动之后的div到浏览器左边的距离(left)
var Tl = e.
clientY - lT
; //计算移动之后的div到浏览器上边的距离(top)
var MaxW=
document.
documentElement.
clientWidth-obox.
offsetWidth; //浏览器视窗宽度-元素实际宽度
var MaxH=
document.
documentElement.
clientHeight-obox.
offsetHeight; //浏览器视窗高度-元素实际高度
//不超过左边的边框
if(il<
0)
{
il=
0;
}
//不超过上边的边框
if(Tl<
0)
{
Tl=
0;
}
//不超过右边的边框
if(il>MaxW)
{
il=MaxW
;
}
//不超过下边的边框
if(Tl>MaxH)
{
Tl=MaxH
;
}
//将值附给obox
obox.
style.
left = il +
'px';
obox.
style.
top = Tl +
'px';
}
;
document.
onmouseup=
function () {
//销毁机制
document.
onmousemove=
null;
document.
onmouseup=
null;
//取消透明层
if(obox.
releaseCapture)
{
obox.
releaseCapture()
;
}
}
;
return false; //阻止浏览器的默认行为,会选中文字
}
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>
转载请注明原文地址: https://www.6miu.com/read-13144.html