拖放位置相对
Drag and drop position relative
为什么当你按下鼠标时,球是相对于位置放置的,它会反弹?绝对定位是指这种情况不会发生。
var ball = document.querySelector('.ball');
ball.onmousedown = function(event) {
var shiftX = event.pageX - getCoords(this).left,
shiftY = event.pageY - getCoords(this).top;
this.style.position = 'relative';
this.zIndex = 10000;
function move(event) {
this.style.left = event.pageX - shiftX + 'px';
this.style.top = event.pageY - shiftY + 'px';
}
move.call(this, event);
document.onmousemove = function(event) {
move.call(ball, event);
};
this.onmouseup = function(event) {
document.onmousemove = this.onmouseup = null;
};
return false;
};
ball.ondragstart = function() {
return false;
};
function getCoords(elem) {
var box = elem.getBoundingClientRect();
return {
top: box.top + window.pageYOffset,
left: box.left + window.pageXOffset
};
}
body {
margin: 50px;
}
img {
cursor: pointer;
}
<img class="ball" src="https://js.cx/clipart/ball.svg" alt="" />
我想这是因为身体元素的填充。请解释一下。
似乎我找到了答案在 JavaScript 中对相对定位的元素实现拖放
正如它所说,在相对位置下,您的元素包含其父标签中所有对象的偏移量和父边距和填充因此,当您尝试获取 elemtn 的位置时,您应该计算它在父级中的实际偏移量,请参阅我的代码示例中使用计数索引
<html>
<body>
<div id=obj1 style="width:100px; height:100px; background:#000; position:relative; " ></div>
<div id=obj2 style="width:100px; height:100px; background:#000; position:relative; " ></div>
<div id=obj3 style="width:100px; height:100px; background:#000; position:relative; " ></div>
<script>
var dragObj, count=0;
function set_drag_drop(obj)
{
if(count>0){
// count margins and divs offset
// body{ margin:10px; }
// height:100px;
obj.adx = 10;
obj.ady = 10 + (count*100)
}else{
obj.adx = 0;
obj.ady = 0;
}
count++;
obj.onmousedown = function(e)
{
var rect = obj.getBoundingClientRect();
obj.dx = rect.left - e.clientX;
obj.dy = rect.top - e.clientY;
obj.isDown = true;
dragObj = this;
}
obj.onmouseup = function(e)
{
obj.isDown = false;
}
document.onmousemove = function(e)
{
if(dragObj && dragObj.isDown)
{
dragObj.style.left = e.pageX -dragObj.adx+ dragObj.dx +"px";
dragObj.style.top = e.pageY -dragObj.ady+ dragObj.dy + "px";
}
}
}
set_drag_drop(document.getElementById("obj1"));
set_drag_drop(document.getElementById("obj2"));
set_drag_drop(document.getElementById("obj3"));
</script>
</html>
相关文章:
- 在不移动元件的情况下从相对位置更改为固定位置
- jQuery拖动到相对位置的可排序列表中时出现可拖动辅助对象位置问题
- 在Appcelerator Titanium中获取视图的相对位置
- kinetic.js绝对线位置,而不是相对位置
- 相对位置和高度100%
- 相对位置上的 UI.位置值错误
- 当下一个元素处于相对位置时,将鼠标悬停在浮点元素上不会触发
- JS:工具提示在图标右侧的相对位置
- 获取元素相对于其父元素的相对位置
- 如何使相对位置像iPhone上的固定位置一样工作
- 在没有鼠标移动事件的情况下跟踪鼠标的相对位置
- 如何找到文本的绝对或相对位置或<br/>在HTML中
- requestFullScreen()只对宽度和相对位置有效吗
- JavaScript从给定宽度和高度的平面数组中确定行、列和元素的相对位置
- 绝对位置和相对位置都不好用
- 定位Div "Fixed"垂直和绝对;水平位置:相对位置;容器Div
- IE7 css块相对位置与Javascript错误
- javascript:改变CSS的相对位置
- 当元素处于相对位置元素时,查找元素偏离窗口的jQuery或JavaScript方法
- 在相对位置中获取滚动条位置