<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1 {width: 100px; height: 100px; background: red; position: absolute;}
#img1 { position: absolute;}
</style>
<script>
window.onload = function() {
var oDiv = document.getElementById('div1');
var oImg = document.getElementById('img1');
drag(oImg);
drag(oDiv);
function drag(obj) {
obj.onmousedown = function(ev) {
var ev = ev || event;
var disX = ev.clientX - this.offsetLeft;
var disY = ev.clientY - this.offsetTop;
if ( obj.setCapture ) {
obj.setCapture();
}
document.onmousemove = function(ev) {
var ev = ev || event;
var L = ev.clientX - disX; //拖动元素左侧的位置=当前鼠标距离浏览器左侧的距离 - (物体宽度的一半)
var T = ev.clientY - disY; //拖动元素顶部的位置=当前鼠标距离浏览器顶部的距离 - (物体高度的一半)
if ( L < 0 ) { //如果左侧的距离小于0,就让距离等于0.不能超出屏幕左侧。如果需要磁性吸附,把0改为100或者想要的数字即可
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;
}
}
}
</script>
</head>
<body>
<div id="div1"></div>
<img src="1.jpg" id="img1" />
</body>
</html>