1、拖動後記錄x,y值
給div加上mousePosition事件
function mousePosition(evt){?
evt = evt || window.event;?
return {?
x : evt.clientX + document.body.scrollLeft - document.body.clientLeft,?
y : evt.clientY + document.body.scrollTop - document.body.clientTop?
}?
}?
2、打開頁面div定位
$(“div”).attr("top",y).attr("left",x);
擴展資料
在用js獲取元素的位置之前,元素在頁面的位置的計算公式,如下:
元素在頁面的位置=此元素相對瀏覽器視窗的位置+瀏覽器滾動條的值;
用getBoundingClientRect()方法來獲得某個元素相對瀏覽器視窗的位置 {這個方法返回的是壹個對象,即Object,該對象具有4個屬性:top,left,right,bottom }。
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Demo</title>
</head>
<body style="width:2000px; height:1000px;">
<div id="demo" style="position:absolute; left:518px; right:100px; width:500px; height:500px;
background:#CC0000; top: 114px;">Demo為了方便就直接用絕對定位的元素</div>
</body>
</html>
<script>
document.getElementById('demo').onclick=function (){
if (document.documentElement.getBoundingClientRect) {
alert("left:"+this.getBoundingClientRect().left)
alert("top:"+this.getBoundingClientRect().top)
alert("right:"+this.getBoundingClientRect().right)
alert("bottom:"+this.getBoundingClientRect().bottom)
var X= this.getBoundingClientRect().left+document.documentElement.scrollLeft;
var Y = this.getBoundingClientRect().top+document.documentElement.scrollTop;
alert("Demo的位置是X:"+X+";Y:"+Y)
}
}
</script>