當前位置:編程學習大全網 - 源碼下載 - js獲取div到body左側距離

js獲取div到body左側距離

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>

  • 上一篇:2021吃雞軍團名字吃雞霸氣的軍團名字
  • 下一篇:xfire集成spring開發webservice怎麽配置發布地址
  • copyright 2024編程學習大全網