Using vanilla JavaScript to work on a panel drag function.
Right now stuck at how to correctly offset the x position of the dragger div so that it does not snap to the right of the cursor.
How would I correct my x
offset below?
http://jsfiddle.net/leongaban/rrcL63y9/41/
window.onload = addListeners();
var xPosition = 0;
function addListeners() {
document.getElementById('drag-container').addEventListener("click", getClickPosition, false);
document.getElementById('dragger').addEventListener('mousedown', mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);
}
function getClickPosition(e) {
xPosition = e.clientX;
console.log(xPosition);
}
function mouseUp() {
window.removeEventListener('mousemove', divMove, true);
}
function mouseDown(e) {
window.addEventListener('mousemove', divMove, true);
}
function divMove(e) {
var max = 443;
var x = event.clientX;
if (x > 100 && x < max) {
var div = document.getElementById('dragger');
div.style.position = 'absolute';
div.x = xPosition;
div.style.left = e.clientX + 'px';
}
//console.log(x);
}
You can do it by knowing the width of the draggable element and adjusting the offset to -(width/2);
function divMove(e) {
var max = 443;
var x = event.clientX;
var div = document.getElementById('dragger');
var offset = div.offsetWidth/2;
if (x > (100 + offset) && x < (max+offset)) {
div.style.position = 'absolute';
div.x = xPosition;
div.style.left = (e.clientX - offset) + 'px';
}
//console.log(x);
}
Here is the updated fiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.