拖拽升级
增加吸附效果和范围限制
HTML
<div id="box" class="box">
这里是内容
</div>
<div>
这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部
</div>
CSS
*{
margin:0;
padding:0;
}
.box{
position:absolute;
width:100px;
height:100px;
background-color:red;
left:200px;
}
JavaScript
window.onload=function() {
// 吸附范围
var glueWidth = 100;
var oBox = document.getElementById("box");
var orgiHeight = oBox.offsetHeight;
oBox.onmousedown = function(ev){
// 获取鼠标在小块内部的位置(距离)
var oEvent = ev || event;
var disX = oEvent.clientX - this.offsetLeft;
var disY = oEvent.clientY - this.offsetTop;
document.onmousemove = function(ev){
var oEvent = ev || event;
var l = oEvent.clientX - disX;
var t = oEvent.clientY - disY;
var viewHeight = document.documentElement.clientHeight,
viewWidth = document.documentElement.clientWidth;
var rangeW = viewWidth - oBox.offsetWidth,
rangeH = viewHeight - orgiHeight;
l = l < glueWidth ? 0 : l; // 吸附效果1
/*
// 吸附效果2
if(l < glueWidth) {
l = 0;
oBox.style.height = viewHeight+'px';
t = 0;
}
else {
oBox.style.height = orgiHeight + "px";
}; */
// 范围限制
l = l > rangeW ? rangeW : l;
t = t < 0 ? 0 : t;
t = t > rangeH ? rangeH : t;
oBox.style.left = l + "px";
oBox.style.top = t + "px";
};
document.onmouseup = function(){
document.onmousemove = document.onmouseup = null;
if(oBox.setCapture){
oBox.releaseCapture();
}
};
// 避免选中文本
if(oBox.setCapture){
oBox.setCapture();
}
return false;
};
};