纯js版的拖拽框,该效果很简单 直接看代码.....
<!doctype html>
<html>
<head>
<meta charset="urf-8"/>
<style>
#box{
border:1px solid #ccc;
position:absolute;
border-radius:4px;
border-shadow:10px 10px 5px #888888;
}
#box h1{
margin:0;
padding:3px;
background:#141414;
color:#fff;
height:32px;
line-height:32px;
text-align:center;
font-size:12px;
cursor:move;
}
</style>
</head>
<body>
<input id="xy_text" style="margin:30px;width:400px;height:30px;line-height:30px;font-size:22px;"/>
<div id="box" style="width:480px;height:200px;"> <!-- 此处需要行内样式,否则使用 document.getElementById('box').style.width 获取不到值使用jq就可以 -->
<h1 id="title">标题</h1>
</div>
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
window.onload = init;
function getHeight(){
return window.innerHeight || document.documentElement && document.documentElement.clientHeight ||
document.body.clientHeight;
}
function getWidth(){
return window.innerWidth || document.documentElement && document.documentElement.clientWidth ||
document.body.clientWidth;
}
function init(){
//鼠标按下去
var titleDom = $('title');
titleDom.onmousedown = mousedown;
document.onmousemove = mousemove;
document.onmouseout = mouseup;
document.onmouseup = mouseup;
var boxDom = $('box');
var width = parseInt(boxDom.style.width);
var height = parseInt(boxDom.style.height);
var bodyWidth = getWidth();
var bodyHeight = getHeight();
boxDom.style.top = (bodyHeight - height)/2 + 'px';
boxDom.style.left = (bodyWidth - width)/2 + 'px';
}
var t = 0, l = 0 , x = 0 , y = 0 ,isover = false;
function mousedown(event){
var e = event || window.event;
x = e.clientX;
y = e.clientY;
var boxDom = $('box');
l = parseInt(boxDom.style.left);
t = parseInt(boxDom.style.top);
isover = true;
}
function mousemove(event){
if(isover){
var e = event || window.event;
var newLeft = l + e.clientX - x;
var newTop = t + e.clientY - y;
$('xy_text').value = 'newLeft = '+newLeft + ' , newTop = '+newTop;
var boxDom = $('box');
if(newTop <= 0)newTop=0;
if(newLeft <= 0)newLeft=0;
var maxLeft = getWidth() - parseInt(boxDom.style.width);
var maxTop = getHeight() - parseInt(boxDom.style.height);
if(newLeft >= maxLeft)newLeft=maxLeft;
if(newTop >= maxTop)newTop=maxTop;
boxDom.style.top = newTop+'px';
boxDom.style.left = newLeft+'px';
}
}
function mouseup(event){
if(isover){
isover = false;
$('xy_text').value = isover;
}
}
</script>
</body>
</html>