|
CS479/579 - Web Programming II
|
Displaying ./code/ES/position.html
<!-- A comment -->
<!DOCTYPE html>
<html onmousedown='grab(event);' onmouseup='drop();' onmousemove='move(event);'>
<head>
<title> Positioning </title>
<meta charset='utf-8'>
<!--
<link rel='stylesheet' src='styles.css' type='text/css' />
-->
<style>
/**
* Make boxes 100x100 picles with a 1px dashed border. Center the
* text inside of the box and position the boxes absolutely. We set
* the line-height to almost the size of the vertical area so the
* text can be vertically centered within it.
*/
.box {
width: 100px; height: 100px; border: 1px dashed black;
line-height: 95px;
text-align: center; vertical-align: middle;
position: absolute;
}
</style>
<script>
// Global for the object that is being dragged:
var obj = null;
/**
* Used to determine the x,y offset of the box to be moved.
*/
function offsets(e) {
var xo = 0, yo = 0;
do {
xo += e.offsetLeft;
yo += e.offsetTop;
} while (e = e.offsetParent);
return {xo : xo, yo : yo};
}
/**
* On mouse-down see if the element (ev) being clicked on (ev.target) is one
* of the boxes (className == "box"), if so, get it's x,y offset and setup the
* obj global.
*/
function grab(ev) {
if (ev.target.className != "box") return;
ev.preventDefault();
var off = offsets(ev.target);
// Adjust the offsets (xo,yo) with respect to the mouse, so the mouse position
// of the cursor remains relative to the boxes upper/left corner.
obj = { e: ev.target, xo: ev.clientX - off.xo, yo: ev.clientY - off.yo };
}
// Reset obj back to null on drop.
function drop() {
obj = null;
}
/**
* If we're moving an object (i.e. obj != null) then adjust it's location by
* adjusting the top/left style settings. Note all style information is a
* CSS string, thus the appending of the "px" unit to the x,y coordinates.
*/
function move(ev) {
if (obj == null) return;
obj.e.style.top = (ev.clientY-obj.yo) + "px";
obj.e.style.left = (ev.clientX-obj.xo) + "px";
}
</script>
</head>
<body>
<div class='box'> A </div>
<div class='box' style='top: 200px;'> B </div>
<div class='box' style='left: 200px;'> C </div>
<div class='box' style='right: 200px;'> D </div>
<div class='box' style='bottom: 200px;'> E </div>
</body>
</html>
|