码迷,mamicode.com
首页 > Web开发 > 详细

原生js 封装 拖拽限制范围

时间:2015-12-13 17:08:51      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

<div id="div1"></div>
<div id="div2"></div>

 

window.onload = function() {

var div1 = document.getElementById(‘div1‘);
var div2 = document.getElementById(‘div2‘);

drag(div1);
drag(div2);

}

function drag(obj) {
obj.onmousedown = function(ev) {
var e = ev || event;
var disX = e.clientX - this.offsetLeft;
var disY = e.clientY - this.offsetTop;

if (obj.setCapture) {
obj.setCapture();
}

document.onmousemove = function(ev) {
var e = ev || event;

var L = e.clientX - disX;
var T = e.clientY - disY;

if (L < 0) {
L = 0;
} else if (L > document.documentElement.clientWidth - obj.offsetWidth) {
L = document.documentElement.clientWidth - obj.offsetWidth;
}
if (T < 0) {
T = 0;
} else if (T > document.documentElement.clientHeight - obj.offsetHeight) {
T = document.documentElement.clientHeight - obj.offsetHeight;
}

obj.style.left = L + ‘px‘;
obj.style.top = T + ‘px‘;
}

document.onmouseup = function() {
document.onmousemove = document.onmouseup = null;
if (obj.releaseCapture) {
obj.releaseCapture();
}
}

return false;
}
}

原生js 封装 拖拽限制范围

标签:

原文地址:http://www.cnblogs.com/tritri/p/5042919.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!