[英]How to fix the offset x position of this div on click?
使用香草JavaScript來面板拖動功能。
現在停留在如何正確偏移拖動器div的x位置,以使其不捕捉到光標的右側。
我如何在下面校正我的x
偏移量?
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);
}
您可以通過了解可拖動元素的寬度並將偏移量調整為-(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);
}
這是更新的小提琴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.