<!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-color: red;
}
</style>
<script>
window.onload = function () {
var oBox = document.getElementById('box'),
iWinW = document.documentElement.clientWidth,
iWinH = document.documentElement.clientHeight;
//做拖拽效果
//添加鼠标摁下的事件
oBox.onmousedown = function (ev) {
var ev = ev || window.event,
iX = ev.clientX - oBox.offsetLeft,
iY = ev.clientY - oBox.offsetTop;
//在低版本IE浏览器下
if(oBox.setCapture){
oBox.setCapture();
}
document.onmousemove = function (ev) {
var ev = ev || window.event,
iL = ev.clientX - iX,
iT = ev.clientY - iY;
//限定拖拽范围
//限定左侧
if(iL < 0){
iL = 0;
}
//限定上侧
if(iT < 0){
iT = 0;
}
//限定右侧
if(iL > iWinW - oBox.offsetWidth){
iL = iWinW - oBox.offsetWidth;
}
//限定下侧
if(iT > iWinH - oBox.offsetHeight){
iT = iWinH - oBox.offsetHeight;
}
//开始赋值
oBox.style.left = iL + 'px';
oBox.style.top = iT + 'px';
}
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
if(oBox.releaseCapture){
oBox.releaseCapture();
}
}
//阻止浏览器的默认行为
return false;
}
}
</script>
</head>
<body>
<div id="box"></div>
wenziwanziwanziwenziwanziwanziwenziwanziwanziwenziwanziwanziwenziwanziwanzi
</body>
</html>