Created
December 17, 2013 01:33
-
-
Save roseforyou/7998405 to your computer and use it in GitHub Desktop.
jQuery div drag demo.
demo Url: jsbin.com/AlULIxi/1000
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> | |
<meta charset=utf-8 /> | |
<style> | |
body{ | |
margin:0; | |
padding:0; | |
} | |
#div1 { | |
background-color: red; | |
width: 100px; | |
height: 100px; | |
position: absolute; | |
top: 100px; | |
left: 100px; | |
} | |
#container { | |
border-style: solid; | |
border-color: green; | |
border-width: 2px 4px 6px 8px; | |
width: 450px; | |
height: 600px; | |
position : absolute; | |
top: 20px; | |
left: 20px; | |
} | |
</style> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<div id="container"> | |
<div id="div1"></div> | |
</div> | |
</body> | |
</html> | |
<script> | |
var $block = $('#div1'); | |
var bW = $block.width(); | |
var bH = $block.height(); | |
var $doc = $(document); | |
var $ctr = $('#container'); | |
var cW = $ctr.width(); | |
var cH = $ctr.height(); | |
var cbl = parseInt($ctr.css('border-left-width')); | |
var cbt = parseInt($ctr.css('border-top-width')); | |
var cPos = $ctr.offset(); | |
var cX = cPos.left; | |
var cY = cPos.top; | |
$block.mousedown(function(e){ | |
e.preventDefault(); | |
var blockX = $block.offset().left; | |
var blockY = $block.offset().top; | |
var mouseX = e.pageX; | |
var mouseY = e.pageY; | |
$doc.mousemove(function(e){ | |
var x = e.pageX - mouseX; | |
var y = e.pageY - mouseY; | |
var nowX = blockX + x; | |
var nowY = blockY + y; | |
if(nowX<=cX+cbl) nowX = cX+cbl; | |
if(nowX>=cX+cW-bW+cbl) nowX = cX + cW - bW + cbl; | |
if(nowY<=cY+cbt) nowY = cY + cbt; | |
if(nowY>=cY+cH-bH+cbt) nowY = cY+ cH - bH + cbt; | |
$block.offset({ | |
left: nowX, | |
top: nowY | |
}); | |
}); | |
}); | |
$doc.mouseup(function(){ | |
$doc.unbind('mousemove'); | |
}); | |
document.onselectstart=function(){return false}; | |
</script> | |
<!-- | |
</body> | |
</html> | |
--> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment