您的位置:首页 > 理论基础 > 计算机网络

js实现拖拽(参考网络)

2015-07-28 16:03 537 查看
<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8" />
<title>js实现拖拽</title>
<style>
#water{
width:400px;
height:188px;
background-color: #ff6600;
}
#water:hover{
cursor: pointer;
}
</style>
</head>
<body>
<div id="water"></div>
<script>
dragInit("water");//调用

//拖拽初始化
function dragInit(id){
var $div = document.getElementById(id);
var style = {
position: "absolute",
left: "0",
top: "0"
}
for(var k in style){
$div.style[k] = style[k];//设置关键css
}
$div.onmousedown = function(e){//鼠标按键按下
e = e || window.event;
var x = e.clientX - $div.offsetLeft;//鼠标到左上角的距离信息, 固定不变
var y = e.clientY - $div.offsetTop;

document.onmousemove = function(e){//鼠标移动
e = e || window.event;
var L = e.clientX - x;
var T = e.clientY - y;

var pW = document.documentElement.clientWidth;//页面宽度
var pH = document.documentElement.clientHeight;
var divW = $div.offsetWidth;//Dom宽度
var divH = $div.offsetHeight;

// 范围限定
if(L < 0){
L = 0;
}
if(T < 0){
T = 0;
}
if(L > pW - divW){
L = pW - divW;
}
if(T > pH - divH){
T = pH - divH;
}
// 范围限定 end

$div.style.left = L + "px";
$div.style.top = T + "px";
};

document.onmouseup = function(e){//鼠标按键松开
document.onmousemove = null;
};
};
}
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: